diff --git a/build.gradle b/build.gradle index fbb0fc3..22efded 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { } group = 'net.foulest' -version = '1.1.4' +version = '1.1.5' description = 'PixelAddons' // Set the project's language level diff --git a/src/main/java/net/foulest/pixeladdons/cmds/EndBattleCmd.java b/src/main/java/net/foulest/pixeladdons/cmds/EndBattleCmd.java index dc95460..f7b7a32 100644 --- a/src/main/java/net/foulest/pixeladdons/cmds/EndBattleCmd.java +++ b/src/main/java/net/foulest/pixeladdons/cmds/EndBattleCmd.java @@ -68,7 +68,8 @@ public void onCommand(@NotNull CommandArgs args) throws CommandException { return; } - EntityPlayerMP playerMP = PixelmonCommand.requireEntityPlayer(player.getName()); + String playerName = player.getName(); + EntityPlayerMP playerMP = PixelmonCommand.requireEntityPlayer(playerName); BattleControllerBase battleController = BattleRegistry.getBattle(playerMP); // Checks if the player is in a battle. diff --git a/src/main/java/net/foulest/pixeladdons/cmds/HatchCmd.java b/src/main/java/net/foulest/pixeladdons/cmds/HatchCmd.java index 9f1728f..5268f4e 100644 --- a/src/main/java/net/foulest/pixeladdons/cmds/HatchCmd.java +++ b/src/main/java/net/foulest/pixeladdons/cmds/HatchCmd.java @@ -20,6 +20,7 @@ import com.pixelmonmod.pixelmon.Pixelmon; import com.pixelmonmod.pixelmon.api.economy.IPixelmonBankAccount; import com.pixelmonmod.pixelmon.api.pokemon.Pokemon; +import com.pixelmonmod.pixelmon.enums.EnumSpecies; import com.pixelmonmod.pixelmon.storage.PlayerPartyStorage; import net.foulest.pixeladdons.PixelAddons; import net.foulest.pixeladdons.data.PlayerData; @@ -34,6 +35,7 @@ import java.text.DecimalFormat; import java.util.Optional; +import java.util.UUID; /** * Command for hatching a Pokemon egg. @@ -71,7 +73,8 @@ public void onCommand(@NotNull CommandArgs args) { return; } - PlayerPartyStorage party = Pixelmon.storageManager.getParty(player.getUniqueId()); + UUID uniqueId = player.getUniqueId(); + PlayerPartyStorage party = Pixelmon.storageManager.getParty(uniqueId); // Checks if the player has a starter Pokemon. if (!party.starterPicked) { @@ -79,16 +82,18 @@ public void onCommand(@NotNull CommandArgs args) { return; } + String firstArgs = args.getArgs(0); + // Checks if the slot is a number. try { - Integer.parseInt(args.getArgs(0)); + Integer.parseInt(firstArgs); } catch (NumberFormatException ex) { MessageUtil.messagePlayer(player, Settings.commandInvalidUsageMessage .replace("%reason%", "Number is invalid")); return; } - int slot = Integer.parseInt(args.getArgs(0)); + int slot = Integer.parseInt(firstArgs); // Checks if the slot is valid. if (slot <= 0 || slot > 6) { @@ -122,7 +127,8 @@ public void onCommand(@NotNull CommandArgs args) { return; } - Player owner = Bukkit.getPlayer(pokemon.getOwnerPlayerUUID()); + UUID ownerPlayerUUID = pokemon.getOwnerPlayerUUID(); + Player owner = Bukkit.getPlayer(ownerPlayerUUID); // Checks if the owner is valid. if (owner == null) { @@ -132,7 +138,7 @@ public void onCommand(@NotNull CommandArgs args) { } Optional bankAccount - = Pixelmon.moneyManager.getBankAccount(player.getUniqueId()); + = Pixelmon.moneyManager.getBankAccount(uniqueId); // Checks if the player has a bank account. if (!bankAccount.isPresent()) { @@ -140,8 +146,11 @@ public void onCommand(@NotNull CommandArgs args) { return; } + IPixelmonBankAccount account = bankAccount.get(); + int currentBalance = account.getMoney(); + // Checks if the player has enough money. - if (bankAccount.get().getMoney() < Settings.hatchCommandCost) { + if (currentBalance < Settings.hatchCommandCost) { MessageUtil.messagePlayer(player, Settings.notEnoughMoneyMessage .replace("%amount%", formattedCost)); return; @@ -149,16 +158,21 @@ public void onCommand(@NotNull CommandArgs args) { // Handles hatching the egg. if (playerData.isConfirmHatch()) { - bankAccount.get().setMoney(bankAccount.get().getMoney() - Settings.hatchCommandCost); + account.setMoney(currentBalance - Settings.hatchCommandCost); pokemon.hatchEgg(); playerData.setConfirmHatch(false); + + EnumSpecies species = pokemon.getSpecies(); + String pokemonName = species.getPokemonName(); + MessageUtil.messagePlayer(player, Settings.pokemonHatchedMessage - .replace("%pokemon%", pokemon.getSpecies().getPokemonName()) + .replace("%pokemon%", pokemonName) .replace("%amount%", formattedCost)); } else { playerData.setConfirmHatch(true); + MessageUtil.messagePlayer(player, Settings.confirmHatchMessage .replace("%amount%", formattedCost)); diff --git a/src/main/java/net/foulest/pixeladdons/cmds/PixelAddonsCmd.java b/src/main/java/net/foulest/pixeladdons/cmds/PixelAddonsCmd.java index f0dbce0..fbae58d 100644 --- a/src/main/java/net/foulest/pixeladdons/cmds/PixelAddonsCmd.java +++ b/src/main/java/net/foulest/pixeladdons/cmds/PixelAddonsCmd.java @@ -96,12 +96,14 @@ private static void handleHelp(@NotNull CommandSender sender, CommandArgs args) ); int itemsPerPage = 4; - int maxPages = (int) Math.ceil((double) commands.size() / itemsPerPage); + int size = commands.size(); + int maxPages = (int) Math.ceil((double) size / itemsPerPage); int page = 1; if (args.length() > 1) { try { - page = Integer.parseInt(args.getArgs(1)); + String args1 = args.getArgs(1); + page = Integer.parseInt(args1); } catch (NumberFormatException ignored) { } } @@ -112,13 +114,14 @@ private static void handleHelp(@NotNull CommandSender sender, CommandArgs args) } int startIndex = (page - 1) * itemsPerPage; - int endIndex = Math.min(commands.size(), startIndex + itemsPerPage); + int endIndex = Math.min(size, startIndex + itemsPerPage); MessageUtil.messagePlayer(sender, ""); MessageUtil.messagePlayer(sender, "&ePixelAddons Help &7(Page " + page + "/" + maxPages + ")"); for (int i = startIndex; i < endIndex; i++) { - MessageUtil.messagePlayer(sender, commands.get(i)); + String line = commands.get(i); + MessageUtil.messagePlayer(sender, line); } MessageUtil.messagePlayer(sender, ""); diff --git a/src/main/java/net/foulest/pixeladdons/cmds/RerollCmd.java b/src/main/java/net/foulest/pixeladdons/cmds/RerollCmd.java index 5115f0e..dbf03c8 100644 --- a/src/main/java/net/foulest/pixeladdons/cmds/RerollCmd.java +++ b/src/main/java/net/foulest/pixeladdons/cmds/RerollCmd.java @@ -79,6 +79,10 @@ public void onCommand(@NotNull CommandArgs args) { } } + String playerName = player.getName(); + int votingSize = votingToReroll.size(); + int onlineSize = Bukkit.getOnlinePlayers().size(); + // Counts the player's vote and broadcasts it. // If the player has already voted, it removes their vote. if (votingToReroll.contains(player)) { @@ -86,19 +90,19 @@ public void onCommand(@NotNull CommandArgs args) { // Broadcasts the cancellation of the vote. MessageUtil.broadcast(Settings.rerollVoteCancelledMessage - .replace("%player%", player.getName()) - .replace("%votes%", String.valueOf(votingToReroll.size())) - .replace("%online%", String.valueOf(Bukkit.getOnlinePlayers().size()))); + .replace("%player%", playerName) + .replace("%votes%", String.valueOf(votingSize)) + .replace("%online%", String.valueOf(onlineSize))); } else { votingToReroll.add(player); // Only broadcasts the vote if there are other players online. // Otherwise, it would be pointless to broadcast it. - if (Bukkit.getOnlinePlayers().size() > 1) { + if (onlineSize > 1) { MessageUtil.broadcast(Settings.rerollVoteSubmittedMessage - .replace("%player%", player.getName()) - .replace("%votes%", String.valueOf(votingToReroll.size())) - .replace("%online%", String.valueOf(Bukkit.getOnlinePlayers().size()))); + .replace("%player%", playerName) + .replace("%votes%", String.valueOf(votingSize)) + .replace("%online%", String.valueOf(onlineSize))); } } @@ -126,8 +130,9 @@ public static void handleReroll() { // Broadcasts the re-roll. if (votingToReroll.size() == 1) { - MessageUtil.broadcast(Settings.rerollHuntMessageWithPlayer - .replace("%player%", votingToReroll.get(0).getName())); + Player player = votingToReroll.get(0); + String playerName = player.getName(); + MessageUtil.broadcast(Settings.rerollHuntMessageWithPlayer.replace("%player%", playerName)); } else { MessageUtil.broadcast(Settings.rerollHuntMessage); } diff --git a/src/main/java/net/foulest/pixeladdons/cmds/ShowCmd.java b/src/main/java/net/foulest/pixeladdons/cmds/ShowCmd.java index d05e811..3f3517a 100644 --- a/src/main/java/net/foulest/pixeladdons/cmds/ShowCmd.java +++ b/src/main/java/net/foulest/pixeladdons/cmds/ShowCmd.java @@ -29,6 +29,8 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.UUID; + /** * Command for showing the stats of a selected Pokemon. * @@ -62,7 +64,8 @@ public void onCommand(@NotNull CommandArgs args) { return; } - PlayerPartyStorage party = Pixelmon.storageManager.getParty(player.getUniqueId()); + UUID uniqueId = player.getUniqueId(); + PlayerPartyStorage party = Pixelmon.storageManager.getParty(uniqueId); // Checks if the player has a starter Pokemon. if (!party.starterPicked) { @@ -70,16 +73,18 @@ public void onCommand(@NotNull CommandArgs args) { return; } + String firstArgs = args.getArgs(0); + // Checks if the slot is a number. try { - Integer.parseInt(args.getArgs(0)); + Integer.parseInt(firstArgs); } catch (NumberFormatException ex) { MessageUtil.messagePlayer(player, Settings.commandInvalidUsageMessage .replace("%reason%", "Not a number")); return; } - int slot = Integer.parseInt(args.getArgs(0)); + int slot = Integer.parseInt(firstArgs); // Checks if the slot is valid. if (slot <= 0 || slot > 6) { @@ -106,7 +111,8 @@ public void onCommand(@NotNull CommandArgs args) { return; } - Player owner = Bukkit.getPlayer(pokemon.getOwnerPlayerUUID()); + UUID ownerPlayerUUID = pokemon.getOwnerPlayerUUID(); + Player owner = Bukkit.getPlayer(ownerPlayerUUID); // Checks if the owner is valid. if (owner == null) { @@ -116,10 +122,11 @@ public void onCommand(@NotNull CommandArgs args) { } String pokemonName = pokemon.getSpecies().getPokemonName(); + String ownerName = owner.getName(); // Handles printing the stats. String chatMessage = Settings.showMessage - .replace("%player%", owner.getName()) + .replace("%player%", ownerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); diff --git a/src/main/java/net/foulest/pixeladdons/cmds/StatsCmd.java b/src/main/java/net/foulest/pixeladdons/cmds/StatsCmd.java index 851bf86..fbf7b1f 100644 --- a/src/main/java/net/foulest/pixeladdons/cmds/StatsCmd.java +++ b/src/main/java/net/foulest/pixeladdons/cmds/StatsCmd.java @@ -29,6 +29,8 @@ import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import java.util.UUID; + /** * Command for showing the stats of a selected Pokemon. * @@ -62,17 +64,19 @@ public void onCommand(@NotNull CommandArgs args) { return; } - PlayerPartyStorage party = Pixelmon.storageManager.getParty(player.getUniqueId()); + UUID playerUUID = player.getUniqueId(); + PlayerPartyStorage party = Pixelmon.storageManager.getParty(playerUUID); + String args1 = args.getArgs(1); // Handles viewing other players' stats. - if (args.length() == 2 && !args.getArgs(1).isEmpty()) { + if (args.length() == 2 && !args1.isEmpty()) { // Checks if viewing other players' stats is disabled. if (!Settings.statsCommandViewOtherPlayers) { MessageUtil.messagePlayer(player, Settings.commandNoPermissionMessage); return; } - Player target = Bukkit.getPlayer(args.getArgs(1)); + Player target = Bukkit.getPlayer(args1); // Checks if the player is invalid. if (target == null) { @@ -88,7 +92,8 @@ public void onCommand(@NotNull CommandArgs args) { return; } - party = Pixelmon.storageManager.getParty(target.getUniqueId()); + UUID targetUUID = target.getUniqueId(); + party = Pixelmon.storageManager.getParty(targetUUID); } // Checks if the player has a starter Pokemon. @@ -97,16 +102,18 @@ public void onCommand(@NotNull CommandArgs args) { return; } + String args0 = args.getArgs(0); + // Checks if the slot is a number. try { - Integer.parseInt(args.getArgs(0)); + Integer.parseInt(args0); } catch (NumberFormatException ex) { MessageUtil.messagePlayer(player, Settings.commandInvalidUsageMessage .replace("%reason%", "Number is invalid")); return; } - int slot = Integer.parseInt(args.getArgs(0)); + int slot = Integer.parseInt(args0); // Checks if the slot is valid. if (slot <= 0 || slot > 6) { @@ -133,7 +140,8 @@ public void onCommand(@NotNull CommandArgs args) { return; } - Player owner = Bukkit.getPlayer(pokemon.getOwnerPlayerUUID()); + UUID ownerPlayerUUID = pokemon.getOwnerPlayerUUID(); + Player owner = Bukkit.getPlayer(ownerPlayerUUID); // Checks if the owner is missing. if (owner == null) { diff --git a/src/main/java/net/foulest/pixeladdons/data/PlayerData.java b/src/main/java/net/foulest/pixeladdons/data/PlayerData.java index 8157ce3..7c10c4e 100644 --- a/src/main/java/net/foulest/pixeladdons/data/PlayerData.java +++ b/src/main/java/net/foulest/pixeladdons/data/PlayerData.java @@ -17,17 +17,13 @@ */ package net.foulest.pixeladdons.data; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; +import lombok.Data; import org.bukkit.entity.Player; import java.util.UUID; -@Getter -@Setter -@ToString -public final class PlayerData { +@Data +public class PlayerData { // Player data private UUID uniqueId; diff --git a/src/main/java/net/foulest/pixeladdons/data/PlayerDataManager.java b/src/main/java/net/foulest/pixeladdons/data/PlayerDataManager.java index 86ee624..e8a6e57 100644 --- a/src/main/java/net/foulest/pixeladdons/data/PlayerDataManager.java +++ b/src/main/java/net/foulest/pixeladdons/data/PlayerDataManager.java @@ -17,8 +17,7 @@ */ package net.foulest.pixeladdons.data; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; +import lombok.Data; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -26,8 +25,8 @@ import java.util.Map; import java.util.UUID; -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class PlayerDataManager { +@Data +public class PlayerDataManager { // Map of player UUIDs to their stored data. private static final Map playerDataMap = new HashMap<>(); @@ -39,12 +38,14 @@ public final class PlayerDataManager { * @return The player's data. */ public static PlayerData getPlayerData(@NotNull Player player) { - if (playerDataMap.containsKey(player.getUniqueId())) { - return playerDataMap.get(player.getUniqueId()); + UUID uniqueId = player.getUniqueId(); + + if (playerDataMap.containsKey(uniqueId)) { + return playerDataMap.get(uniqueId); } else { addPlayerData(player); } - return playerDataMap.get(player.getUniqueId()); + return playerDataMap.get(uniqueId); } /** @@ -53,9 +54,11 @@ public static PlayerData getPlayerData(@NotNull Player player) { * @param player The player to add. */ private static void addPlayerData(@NotNull Player player) { - if (!playerDataMap.containsKey(player.getUniqueId())) { - PlayerData data = new PlayerData(player.getUniqueId(), player); - playerDataMap.put(player.getUniqueId(), data); + UUID uniqueId = player.getUniqueId(); + + if (!playerDataMap.containsKey(uniqueId)) { + PlayerData data = new PlayerData(uniqueId, player); + playerDataMap.put(uniqueId, data); } } @@ -65,6 +68,7 @@ private static void addPlayerData(@NotNull Player player) { * @param player The player to remove. */ public static void removePlayerData(@NotNull Player player) { - playerDataMap.remove(player.getUniqueId()); + UUID uniqueId = player.getUniqueId(); + playerDataMap.remove(uniqueId); } } diff --git a/src/main/java/net/foulest/pixeladdons/listeners/EventListener.java b/src/main/java/net/foulest/pixeladdons/listeners/EventListener.java index 03289fe..87c4c40 100644 --- a/src/main/java/net/foulest/pixeladdons/listeners/EventListener.java +++ b/src/main/java/net/foulest/pixeladdons/listeners/EventListener.java @@ -32,6 +32,7 @@ import com.pixelmonmod.pixelmon.api.spawning.archetypes.entities.pokemon.SpawnInfoPokemon; import com.pixelmonmod.pixelmon.entities.pixelmon.EntityPixelmon; import com.pixelmonmod.pixelmon.entities.pixelmon.stats.EVStore; +import com.pixelmonmod.pixelmon.enums.EnumSpecies; import com.pixelmonmod.pixelmon.storage.PlayerPartyStorage; import net.foulest.pixeladdons.PixelAddons; import net.foulest.pixeladdons.cmds.RerollCmd; @@ -55,6 +56,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; +import java.util.UUID; public class EventListener implements Listener { @@ -76,7 +78,8 @@ public static void onPlayerJoin(@NotNull PlayerJoinEvent event) { } // Replaces %player% with the player's name. - String replace = line.replace("%player%", player.getName()); + String playerName = player.getName(); + String replace = line.replace("%player%", playerName); // Runs the command as console. Bukkit.dispatchCommand(Bukkit.getConsoleSender(), replace); @@ -118,114 +121,127 @@ public static void onEVGain(@NotNull ForgeEvent event) { // Handles EV gain messages. if (forgeEvent instanceof EVsGainedEvent) { EVsGainedEvent eVsGainedEvent = (EVsGainedEvent) forgeEvent; + EntityPlayerMP ownerPlayer = eVsGainedEvent.pokemon.getOwnerPlayer(); - // Checks if the Pokemon has an owner. - if (eVsGainedEvent.pokemon.getOwnerPlayer() != null - && Bukkit.getPlayer(eVsGainedEvent.pokemon.getOwnerPlayer().getUniqueID()) != null) { - Player player = Bukkit.getPlayer(eVsGainedEvent.pokemon.getOwnerPlayer().getUniqueID()); + // Returns if the owner player is null. + if (ownerPlayer == null) { + return; + } - // Returns if the player is null. - if (player == null) { - return; - } + UUID ownerPlayerUUID = ownerPlayer.getUniqueID(); - EVStore evStore = eVsGainedEvent.evStore; - PlayerPartyStorage party = Pixelmon.storageManager.getParty(player.getUniqueId()); - int[] oldEVs = evStore.getArray(); + // Returns if the owner is null. + if (Bukkit.getPlayer(ownerPlayerUUID) == null) { + return; + } - // Returns if the player is offline. - if (!player.isOnline()) { - return; - } + Player player = Bukkit.getPlayer(ownerPlayerUUID); - // Handles EV gain messages. - new BukkitRunnable() { - @Override - public void run() { - Pokemon pokemon = party.get(party.getSlot(eVsGainedEvent.pokemon.getUUID())); + // Returns if the player is null. + if (player == null) { + return; + } - // Returns if the Pokemon is null. - if (pokemon == null) { - return; - } + EVStore evStore = eVsGainedEvent.evStore; + int[] oldEVs = evStore.getArray(); - // Calculates the EV differences. - int[] newEVs = pokemon.getEVs().getArray(); - int hpDiff = newEVs[0] - oldEVs[0]; - int atkDiff = newEVs[1] - oldEVs[1]; - int defDiff = newEVs[2] - oldEVs[2]; - int spaDiff = newEVs[3] - oldEVs[3]; - int spdDiff = newEVs[4] - oldEVs[4]; - int speDiff = newEVs[5] - oldEVs[5]; - List msgList = new ArrayList<>(); - - if (hpDiff > 0) { - msgList.add(Settings.evIncreaseMessage - .replace("%diff%", String.valueOf(hpDiff)) - .replace("%stat%", "HP") - .replace("%newEVs%", String.valueOf(newEVs[0]))); - } + UUID playerUUID = player.getUniqueId(); + PlayerPartyStorage party = Pixelmon.storageManager.getParty(playerUUID); - if (atkDiff > 0) { - msgList.add(Settings.evIncreaseMessage - .replace("%diff%", String.valueOf(atkDiff)) - .replace("%stat%", "Atk") - .replace("%newEVs%", String.valueOf(newEVs[1]))); - } + // Returns if the player is offline. + if (!player.isOnline()) { + return; + } - if (defDiff > 0) { - msgList.add(Settings.evIncreaseMessage - .replace("%diff%", String.valueOf(defDiff)) - .replace("%stat%", "Def") - .replace("%newEVs%", String.valueOf(newEVs[2]))); - } + // Handles EV gain messages. + new BukkitRunnable() { + @Override + public void run() { + UUID pokemonUUID = eVsGainedEvent.pokemon.getUUID(); + int partySlot = party.getSlot(pokemonUUID); + Pokemon pokemon = party.get(partySlot); - if (spaDiff > 0) { - msgList.add(Settings.evIncreaseMessage - .replace("%diff%", String.valueOf(spaDiff)) - .replace("%stat%", "SpA") - .replace("%newEVs%", String.valueOf(newEVs[3]))); - } + // Returns if the Pokemon is null. + if (pokemon == null) { + return; + } - if (spdDiff > 0) { - msgList.add(Settings.evIncreaseMessage - .replace("%diff%", String.valueOf(spdDiff)) - .replace("%stat%", "SpD") - .replace("%newEVs%", String.valueOf(newEVs[4]))); - } + // Calculates the EV differences. + int[] newEVs = pokemon.getEVs().getArray(); + int hpDiff = newEVs[0] - oldEVs[0]; + int atkDiff = newEVs[1] - oldEVs[1]; + int defDiff = newEVs[2] - oldEVs[2]; + int spaDiff = newEVs[3] - oldEVs[3]; + int spdDiff = newEVs[4] - oldEVs[4]; + int speDiff = newEVs[5] - oldEVs[5]; + List msgList = new ArrayList<>(); + + if (hpDiff > 0) { + msgList.add(Settings.evIncreaseMessage + .replace("%diff%", String.valueOf(hpDiff)) + .replace("%stat%", "HP") + .replace("%newEVs%", String.valueOf(newEVs[0]))); + } - if (speDiff > 0) { - msgList.add(Settings.evIncreaseMessage - .replace("%diff%", String.valueOf(speDiff)) - .replace("%stat%", "Spe") - .replace("%newEVs%", String.valueOf(newEVs[5]))); - } + if (atkDiff > 0) { + msgList.add(Settings.evIncreaseMessage + .replace("%diff%", String.valueOf(atkDiff)) + .replace("%stat%", "Atk") + .replace("%newEVs%", String.valueOf(newEVs[1]))); + } - StringBuilder totalEVsGained = new StringBuilder(); + if (defDiff > 0) { + msgList.add(Settings.evIncreaseMessage + .replace("%diff%", String.valueOf(defDiff)) + .replace("%stat%", "Def") + .replace("%newEVs%", String.valueOf(newEVs[2]))); + } - // Formats the message. - if (!msgList.isEmpty()) { - for (int i = 0; i < msgList.size(); i++) { - totalEVsGained.append(msgList.get(i)); + if (spaDiff > 0) { + msgList.add(Settings.evIncreaseMessage + .replace("%diff%", String.valueOf(spaDiff)) + .replace("%stat%", "SpA") + .replace("%newEVs%", String.valueOf(newEVs[3]))); + } - if (i + 1 < msgList.size()) { - totalEVsGained.append(" "); - } - } + if (spdDiff > 0) { + msgList.add(Settings.evIncreaseMessage + .replace("%diff%", String.valueOf(spdDiff)) + .replace("%stat%", "SpD") + .replace("%newEVs%", String.valueOf(newEVs[4]))); + } - String pokemonName = pokemon.getSpecies().getPokemonName(); - String chatMessage = Settings.evGainMessage - .replace("%pokemon%", pokemonName) - .replace("%evGains%", totalEVsGained.toString()); + if (speDiff > 0) { + msgList.add(Settings.evIncreaseMessage + .replace("%diff%", String.valueOf(speDiff)) + .replace("%stat%", "Spe") + .replace("%newEVs%", String.valueOf(newEVs[5]))); + } + + StringBuilder totalEVsGained = new StringBuilder(); + + // Formats the message. + if (!msgList.isEmpty()) { + for (int i = 0; i < msgList.size(); i++) { + totalEVsGained.append(msgList.get(i)); - // Sends the message. - if (player.isOnline()) { - MessageUtil.messagePlayer(player, chatMessage); + if (i + 1 < msgList.size()) { + totalEVsGained.append(" "); } } + + String pokemonName = pokemon.getSpecies().getPokemonName(); + String chatMessage = Settings.evGainMessage + .replace("%pokemon%", pokemonName) + .replace("%evGains%", totalEVsGained.toString()); + + // Sends the message. + if (player.isOnline()) { + MessageUtil.messagePlayer(player, chatMessage); + } } - }.runTaskLater(PixelAddons.instance, 5L); - } + } + }.runTaskLater(PixelAddons.instance, 5L); } } @@ -264,7 +280,8 @@ public static void onCustomRateSpawn(@NotNull ForgeEvent event) { } // Gets the player that spawned the Pokemon. - Player player = Bukkit.getPlayer(spawnLocation.cause.getName()); + String playerName = spawnLocation.cause.getName(); + Player player = Bukkit.getPlayer(playerName); if (player == null || !player.isOnline()) { return; } @@ -286,7 +303,7 @@ && new Random().nextInt(Settings.customShinyRateOdds) == 0) { spawnAction.usingSpec.apply(pixelmon); } - // Sets the custom pokerus rate for qualifying players. + // Sets the custom Pokerus rate for qualifying players. if (Settings.customPokerusRateEnabled && player.hasPermission(Settings.customPokerusRatePermission) && new Random().nextInt(Settings.customPokerusRateOdds) == 0) { spawnAction.usingSpec.pokerusType = (byte) (new Random().nextInt(5) + 1); @@ -320,11 +337,13 @@ public static void onPokemonCatch(@NotNull ForgeEvent event) { // Differentiates the handling based on the event type. if (forgeEvent instanceof CaptureEvent.SuccessfulCapture) { CaptureEvent.SuccessfulCapture captureEvent = (CaptureEvent.SuccessfulCapture) forgeEvent; - player = Bukkit.getPlayer(captureEvent.player.getUniqueID()); + UUID uniqueID = captureEvent.player.getUniqueID(); + player = Bukkit.getPlayer(uniqueID); pokemon = captureEvent.getPokemon().getStoragePokemonData(); } else { CaptureEvent.SuccessfulRaidCapture captureEvent = (CaptureEvent.SuccessfulRaidCapture) forgeEvent; - player = Bukkit.getPlayer(captureEvent.player.getUniqueID()); + UUID uniqueID = captureEvent.player.getUniqueID(); + player = Bukkit.getPlayer(uniqueID); pokemon = captureEvent.getRaidPokemon(); } @@ -339,12 +358,12 @@ && new Random().nextInt(Settings.customHiddenAbilityRateOdds) == 0) { pokemon.setAbilitySlot(2); } - // Gets the Pokemon's name. pokemonName = pokemon.getSpecies().getPokemonName(); + String playerName = player.getName(); // Formats the hover message. String chatMessage = Settings.catchMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); @@ -360,7 +379,8 @@ public void run() { // Handles Pokemon pickup messages. if (forgeEvent instanceof PickupEvent) { PickupEvent pickupEvent = (PickupEvent) forgeEvent; - Player player = Bukkit.getPlayer(pickupEvent.player.player.getUniqueID()); + UUID uniqueID = pickupEvent.player.player.getUniqueID(); + Player player = Bukkit.getPlayer(uniqueID); Pokemon pokemon = pickupEvent.pokemon.pokemon; ItemStack itemStack = pickupEvent.stack; @@ -389,9 +409,12 @@ public void run() { || (!itemName.isEmpty() && itemName.charAt(0) == 'O') || (!itemName.isEmpty() && itemName.charAt(0) == 'U')) ? "n" : ""); + EnumSpecies species = pokemon.getSpecies(); + String pokemonName = species.getPokemonName(); + // Formats the message. String chatMessage = Settings.pickupMessage - .replace("%pokemon%", pokemon.getSpecies().getPokemonName()) + .replace("%pokemon%", pokemonName) .replace("%an%", article) .replace("%color%", Settings.pickupColor) .replace("%itemName%", itemName); @@ -403,8 +426,10 @@ public void run() { // Handles egg hatch messages. if (forgeEvent instanceof EggHatchEvent.Post) { EggHatchEvent.Post eggHatchEvent = (EggHatchEvent.Post) forgeEvent; - Player player = Bukkit.getPlayer(eggHatchEvent.getPokemon().getOwnerPlayer().getUniqueID()); Pokemon pokemon = eggHatchEvent.getPokemon(); + EntityPlayerMP ownerPlayer = pokemon.getOwnerPlayer(); + UUID ownerPlayerUUID = ownerPlayer.getUniqueID(); + Player player = Bukkit.getPlayer(ownerPlayerUUID); String pokemonName = pokemon.getSpecies().getPokemonName(); // Returns if the player is null. @@ -417,9 +442,11 @@ public void run() { return; } + String playerName = player.getName(); + // Formats the message. String chatMessage = Settings.eggHatchMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); @@ -430,7 +457,8 @@ public void run() { // Handles Pokemon receive messages. if (forgeEvent instanceof PixelmonReceivedEvent) { PixelmonReceivedEvent receivedEvent = (PixelmonReceivedEvent) forgeEvent; - Player player = Bukkit.getPlayer(receivedEvent.player.getUniqueID()); + UUID uniqueID = receivedEvent.player.getUniqueID(); + Player player = Bukkit.getPlayer(uniqueID); Pokemon pokemon = receivedEvent.pokemon; String pokemonName = pokemon.getSpecies().getPokemonName(); ReceiveType receiveType = receivedEvent.receiveType; @@ -446,12 +474,13 @@ public void run() { } String chatMessage = ""; + String playerName = player.getName(); // Formats the message. switch (receiveType) { case Custom: chatMessage = Settings.receivePokemonCustomMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); break; @@ -465,7 +494,7 @@ public void run() { || (!pokemonName.isEmpty() && pokemonName.charAt(0) == 'U')) ? "n" : ""); chatMessage = Settings.fossilRevivalMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%an%", article) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); @@ -473,28 +502,28 @@ public void run() { case Starter: chatMessage = Settings.chooseStarterMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); break; case Command: chatMessage = Settings.receivePokemonCommandMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); break; case SelectPokemon: chatMessage = Settings.receivePokemonSelectMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); break; case Christmas: chatMessage = Settings.receivePokemonChristmasMessage - .replace("%player%", player.getName()) + .replace("%player%", playerName) .replace("%color%", FormatUtil.getDisplayColor(pokemon)) .replace("%pokemon%", pokemonName); break; diff --git a/src/main/java/net/foulest/pixeladdons/util/FormatUtil.java b/src/main/java/net/foulest/pixeladdons/util/FormatUtil.java index 884a3b6..568a2b0 100644 --- a/src/main/java/net/foulest/pixeladdons/util/FormatUtil.java +++ b/src/main/java/net/foulest/pixeladdons/util/FormatUtil.java @@ -18,8 +18,7 @@ package net.foulest.pixeladdons.util; import com.pixelmonmod.pixelmon.api.pokemon.Pokemon; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; +import lombok.Data; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; @@ -28,8 +27,8 @@ * * @author Foulest */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class FormatUtil { +@Data +public class FormatUtil { /** * Gets the display color of a Pokemon. diff --git a/src/main/java/net/foulest/pixeladdons/util/HiddenPowerUtil.java b/src/main/java/net/foulest/pixeladdons/util/HiddenPowerUtil.java index 8ca6f2b..2d8edae 100644 --- a/src/main/java/net/foulest/pixeladdons/util/HiddenPowerUtil.java +++ b/src/main/java/net/foulest/pixeladdons/util/HiddenPowerUtil.java @@ -20,8 +20,7 @@ import com.pixelmonmod.pixelmon.api.pokemon.Pokemon; import com.pixelmonmod.pixelmon.entities.pixelmon.stats.StatsType; import com.pixelmonmod.pixelmon.enums.EnumType; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; +import lombok.Data; import org.jetbrains.annotations.NotNull; /** @@ -30,8 +29,8 @@ * @author Foulest * @project PixelAddons */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -final class HiddenPowerUtil { +@Data +class HiddenPowerUtil { /** * Gets the hidden power type of a Pokemon. diff --git a/src/main/java/net/foulest/pixeladdons/util/MessageUtil.java b/src/main/java/net/foulest/pixeladdons/util/MessageUtil.java index aeb5979..047f1a2 100644 --- a/src/main/java/net/foulest/pixeladdons/util/MessageUtil.java +++ b/src/main/java/net/foulest/pixeladdons/util/MessageUtil.java @@ -18,8 +18,8 @@ package net.foulest.pixeladdons.util; import com.pixelmonmod.pixelmon.api.pokemon.Pokemon; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; +import lombok.Data; +import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.HoverEvent; import net.md_5.bungee.api.chat.TextComponent; @@ -44,9 +44,9 @@ * * @author Foulest */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) +@Data @SuppressWarnings("unused") -public final class MessageUtil { +public class MessageUtil { private static final Logger logger = Bukkit.getLogger(); @@ -184,12 +184,16 @@ public static void printStatsHoverMessage(Player player, for (Player online : Bukkit.getOnlinePlayers()) { TextComponent message = new TextComponent(colorize(chatMessage)); TextComponent newLine = new TextComponent(ComponentSerializer.parse("{text: \"\n\"}")); - TextComponent hoverMessage = new TextComponent(new ComponentBuilder("").create()); + + BaseComponent[] components = new ComponentBuilder("").create(); + TextComponent hoverMessage = new TextComponent(components); for (String line : statsList) { hoverMessage.addExtra(new TextComponent(colorize(line))); - if (!statsList.get(statsList.size() - 1).equals(line)) { + int size = statsList.size(); + + if (!statsList.get(size - 1).equals(line)) { hoverMessage.addExtra(newLine); } } diff --git a/src/main/java/net/foulest/pixeladdons/util/Settings.java b/src/main/java/net/foulest/pixeladdons/util/Settings.java index 8944bc8..ff39d44 100644 --- a/src/main/java/net/foulest/pixeladdons/util/Settings.java +++ b/src/main/java/net/foulest/pixeladdons/util/Settings.java @@ -17,7 +17,8 @@ */ package net.foulest.pixeladdons.util; -import lombok.*; +import lombok.Cleanup; +import lombok.Data; import net.foulest.pixeladdons.PixelAddons; import net.foulest.pixeladdons.util.yaml.CustomYamlConfiguration; import org.bukkit.configuration.file.FileConfiguration; @@ -36,11 +37,9 @@ * * @author Foulest */ -@Getter -@Setter -@NoArgsConstructor(access = AccessLevel.PRIVATE) +@Data @SuppressWarnings("WeakerAccess") -public final class Settings { +public class Settings { // File settings public static File file; diff --git a/src/main/java/net/foulest/pixeladdons/util/StatsUtil.java b/src/main/java/net/foulest/pixeladdons/util/StatsUtil.java index bbe6c3b..6d03ebe 100644 --- a/src/main/java/net/foulest/pixeladdons/util/StatsUtil.java +++ b/src/main/java/net/foulest/pixeladdons/util/StatsUtil.java @@ -18,12 +18,15 @@ package net.foulest.pixeladdons.util; import com.pixelmonmod.pixelmon.api.pokemon.Pokemon; +import com.pixelmonmod.pixelmon.entities.pixelmon.abilities.AbilityBase; import com.pixelmonmod.pixelmon.entities.pixelmon.stats.Gender; +import com.pixelmonmod.pixelmon.entities.pixelmon.stats.IVStore; +import com.pixelmonmod.pixelmon.entities.pixelmon.stats.Pokerus; import com.pixelmonmod.pixelmon.entities.pixelmon.stats.StatsType; import com.pixelmonmod.pixelmon.enums.EnumNature; import com.pixelmonmod.pixelmon.enums.EnumPokerusType; -import lombok.AccessLevel; -import lombok.NoArgsConstructor; +import com.pixelmonmod.pixelmon.enums.EnumSpecies; +import lombok.Data; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -33,8 +36,8 @@ import java.util.List; import java.util.Map; -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class StatsUtil { +@Data +public class StatsUtil { /** * Gets the stats panel of a Pokemon. @@ -56,26 +59,54 @@ public final class StatsUtil { int speedEV = pokemon.getEVs().getStat(StatsType.Speed); // Get the IVs of the Pokemon - int hpIV = pokemon.getIVs().getStat(StatsType.HP); - int attackIV = pokemon.getIVs().getStat(StatsType.Attack); - int defenceIV = pokemon.getIVs().getStat(StatsType.Defence); - int spAttackIV = pokemon.getIVs().getStat(StatsType.SpecialAttack); - int spDefenceIV = pokemon.getIVs().getStat(StatsType.SpecialDefence); - int speedIV = pokemon.getIVs().getStat(StatsType.Speed); + IVStore iVs = pokemon.getIVs(); + int hpIV = iVs.getStat(StatsType.HP); + int attackIV = iVs.getStat(StatsType.Attack); + int defenceIV = iVs.getStat(StatsType.Defence); + int spAttackIV = iVs.getStat(StatsType.SpecialAttack); + int spDefenceIV = iVs.getStat(StatsType.SpecialDefence); + int speedIV = iVs.getStat(StatsType.Speed); + + String playerName = player.getName(); + boolean isEgg = pokemon.isEgg(); + EnumSpecies species = pokemon.getSpecies(); + String pokemonName = species.getPokemonName(); + boolean shiny = pokemon.isShiny(); + Pokerus pokerus = pokemon.getPokerus(); + Gender gender = pokemon.getGender(); + int level = pokemon.getLevel(); + AbilityBase ability = pokemon.getAbility(); + String abilityName = ability.getLocalizedName(); + EnumNature nature = pokemon.getNature(); + String natureName = nature.getLocalizedName(); + String hiddenPowerName = HiddenPowerUtil.getHiddenPower(pokemon).getLocalizedName(); + String genderSymbol = ""; + + // Gets the gender symbol for the Pokemon. + switch (gender) { + case Male: + genderSymbol = "&b(M)"; + break; + case Female: + genderSymbol = "&d(F)"; + break; + default: + break; + } // Define all placeholders and their corresponding values Map placeholders = new HashMap<>(); placeholders.put("%color%", FormatUtil.getDisplayColor(pokemon)); - placeholders.put("%player%", player.getName()); - placeholders.put("%pokemon%", (pokemon.isEgg() ? "Egg" : pokemon.getSpecies().getPokemonName())); - placeholders.put("%shinyStar%", pokemon.isShiny() ? " &6★" : ""); - placeholders.put("%PKRS%", (pokemon.getPokerus() != null && pokemon.getPokerus().type != EnumPokerusType.UNINFECTED) ? " &5(PKRS)" : ""); - placeholders.put("%gender%", pokemon.getGender() == Gender.Male ? "&b(M)" : (pokemon.getGender() == Gender.Female ? "&d(F)" : "")); - placeholders.put("%level%", String.valueOf(pokemon.getLevel())); - placeholders.put("%ability%", pokemon.getAbility().getLocalizedName()); - placeholders.put("%nature%", pokemon.getNature().getLocalizedName()); + placeholders.put("%player%", playerName); + placeholders.put("%pokemon%", (isEgg ? "Egg" : pokemonName)); + placeholders.put("%shinyStar%", shiny ? " &6★" : ""); + placeholders.put("%PKRS%", (pokerus != null && pokerus.type != EnumPokerusType.UNINFECTED) ? " &5(PKRS)" : ""); + placeholders.put("%gender%", genderSymbol); + placeholders.put("%level%", String.valueOf(level)); + placeholders.put("%ability%", abilityName); + placeholders.put("%nature%", natureName); placeholders.put("%natureEffect%", getNatureEffect(pokemon)); - placeholders.put("%hiddenPower%", HiddenPowerUtil.getHiddenPower(pokemon).getLocalizedName()); + placeholders.put("%hiddenPower%", hiddenPowerName); placeholders.put("%hpEV%", FormatUtil.evColor(hpEV) + hpEV); placeholders.put("%attackEV%", FormatUtil.evColor(attackEV) + attackEV); @@ -84,12 +115,19 @@ public final class StatsUtil { placeholders.put("%spDefenceEV%", FormatUtil.evColor(spDefenceEV) + spDefenceEV); placeholders.put("%speedEV%", FormatUtil.evColor(speedEV) + speedEV); - placeholders.put("%hpIV%", (pokemon.getIVs().isHyperTrained(StatsType.HP) ? "&6&o" : FormatUtil.ivColor(hpIV)) + hpIV); - placeholders.put("%attackIV%", (pokemon.getIVs().isHyperTrained(StatsType.Attack) ? "&6&o" : FormatUtil.ivColor(attackIV)) + attackIV); - placeholders.put("%defenceIV%", (pokemon.getIVs().isHyperTrained(StatsType.Defence) ? "&6&o" : FormatUtil.ivColor(defenceIV)) + defenceIV); - placeholders.put("%spAttackIV%", (pokemon.getIVs().isHyperTrained(StatsType.SpecialAttack) ? "&6&o" : FormatUtil.ivColor(spAttackIV)) + spAttackIV); - placeholders.put("%spDefenceIV%", (pokemon.getIVs().isHyperTrained(StatsType.SpecialDefence) ? "&6&o" : FormatUtil.ivColor(spDefenceIV)) + spDefenceIV); - placeholders.put("%speedIV%", (pokemon.getIVs().isHyperTrained(StatsType.Speed) ? "&6&o" : FormatUtil.ivColor(speedIV)) + speedIV); + boolean hyperTrainedHP = iVs.isHyperTrained(StatsType.HP); + boolean hyperTrainedAtk = iVs.isHyperTrained(StatsType.Attack); + boolean hyperTrainedDef = iVs.isHyperTrained(StatsType.Defence); + boolean hyperTrainedSpA = iVs.isHyperTrained(StatsType.SpecialAttack); + boolean hyperTrainedSpD = iVs.isHyperTrained(StatsType.SpecialDefence); + boolean hyperTrainedSpe = iVs.isHyperTrained(StatsType.Speed); + + placeholders.put("%hpIV%", (hyperTrainedHP ? "&6&o" : FormatUtil.ivColor(hpIV)) + hpIV); + placeholders.put("%attackIV%", (hyperTrainedAtk ? "&6&o" : FormatUtil.ivColor(attackIV)) + attackIV); + placeholders.put("%defenceIV%", (hyperTrainedDef ? "&6&o" : FormatUtil.ivColor(defenceIV)) + defenceIV); + placeholders.put("%spAttackIV%", (hyperTrainedSpA ? "&6&o" : FormatUtil.ivColor(spAttackIV)) + spAttackIV); + placeholders.put("%spDefenceIV%", (hyperTrainedSpD ? "&6&o" : FormatUtil.ivColor(spDefenceIV)) + spDefenceIV); + placeholders.put("%speedIV%", (hyperTrainedSpe ? "&6&o" : FormatUtil.ivColor(speedIV)) + speedIV); placeholders.put("%evPercent%", getEVPercent(pokemon)); placeholders.put("%ivPercent%", getIVPercent(pokemon)); @@ -99,7 +137,9 @@ public final class StatsUtil { String line = message; for (Map.Entry entry : placeholders.entrySet()) { - line = line.replace(entry.getKey(), entry.getValue()); + String key = entry.getKey(); + String value = entry.getValue(); + line = line.replace(key, value); } statsPanel.add(line); @@ -120,9 +160,12 @@ public final class StatsUtil { StatsType increasedStat = nature.increasedStat; StatsType decreasedStat = nature.decreasedStat; + String increasedName = increasedStat.getUnlocalizedName(); + String decreasedName = decreasedStat.getUnlocalizedName(); + // Format the stats - String increasedStatFormatted = FormatUtil.formatStat(increasedStat.getUnlocalizedName()); - String decreasedStatFormatted = FormatUtil.formatStat(decreasedStat.getUnlocalizedName()); + String increasedStatFormatted = FormatUtil.formatStat(increasedName); + String decreasedStatFormatted = FormatUtil.formatStat(decreasedName); // Check if the nature has an effect if (increasedStat == StatsType.None && decreasedStat == StatsType.None) { diff --git a/src/main/java/net/foulest/pixeladdons/util/command/BukkitCommand.java b/src/main/java/net/foulest/pixeladdons/util/command/BukkitCommand.java index d28a08f..9eeada6 100644 --- a/src/main/java/net/foulest/pixeladdons/util/command/BukkitCommand.java +++ b/src/main/java/net/foulest/pixeladdons/util/command/BukkitCommand.java @@ -32,7 +32,7 @@ * @author minnymin3 * @see CommandFramework GitHub */ -class BukkitCommand extends org.bukkit.command.Command { +public class BukkitCommand extends org.bukkit.command.Command { private final Plugin owningPlugin; private final CommandExecutor executor; diff --git a/src/main/java/net/foulest/pixeladdons/util/command/BukkitCompleter.java b/src/main/java/net/foulest/pixeladdons/util/command/BukkitCompleter.java index 186ef6d..d500e36 100644 --- a/src/main/java/net/foulest/pixeladdons/util/command/BukkitCompleter.java +++ b/src/main/java/net/foulest/pixeladdons/util/command/BukkitCompleter.java @@ -17,8 +17,7 @@ */ package net.foulest.pixeladdons.util.command; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabCompleter; @@ -35,9 +34,8 @@ * @author minnymin3 * @see CommandFramework GitHub */ -@Getter -@Setter -class BukkitCompleter implements TabCompleter { +@Data +public class BukkitCompleter implements TabCompleter { private final Map> completers = new HashMap<>(); @@ -83,8 +81,9 @@ public List onTabComplete(@NotNull CommandSender sender, Map.Entry entry = completers.get(cmdLabel); try { - return (List) entry.getKey().invoke(entry.getValue(), - new CommandArgs(sender, command, label, args, cmdLabel.split("\\.").length - 1)); + Object value = entry.getValue(); + String[] split = cmdLabel.split("\\."); + return (List) entry.getKey().invoke(value, new CommandArgs(sender, command, label, args, split.length - 1)); } catch (IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) { ex.printStackTrace(); } diff --git a/src/main/java/net/foulest/pixeladdons/util/command/CommandArgs.java b/src/main/java/net/foulest/pixeladdons/util/command/CommandArgs.java index 88268d4..9facb3f 100644 --- a/src/main/java/net/foulest/pixeladdons/util/command/CommandArgs.java +++ b/src/main/java/net/foulest/pixeladdons/util/command/CommandArgs.java @@ -17,8 +17,7 @@ */ package net.foulest.pixeladdons.util.command; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; @@ -32,8 +31,7 @@ * @author minnymin3 * @see CommandFramework GitHub */ -@Getter -@Setter +@Data public class CommandArgs { private final CommandSender sender; diff --git a/src/main/java/net/foulest/pixeladdons/util/command/CommandFramework.java b/src/main/java/net/foulest/pixeladdons/util/command/CommandFramework.java index 2dd3872..6c1882c 100644 --- a/src/main/java/net/foulest/pixeladdons/util/command/CommandFramework.java +++ b/src/main/java/net/foulest/pixeladdons/util/command/CommandFramework.java @@ -17,8 +17,7 @@ */ package net.foulest.pixeladdons.util.command; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; import net.foulest.pixeladdons.util.MessageUtil; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandMap; @@ -42,8 +41,7 @@ * @author minnymin3 * @see CommandFramework GitHub */ -@Getter -@Setter +@Data public class CommandFramework implements CommandExecutor { private final Map> commandMap = new HashMap<>(); @@ -77,7 +75,9 @@ public CommandFramework(@NotNull Plugin plugin) { * @param args The CommandArgs object representing the command arguments. */ private static void defaultCommand(@NotNull CommandArgs args) { - args.getSender().sendMessage(args.getLabel() + " is disabled on this server."); + String label = args.getLabel(); + CommandSender commandSender = args.getSender(); + MessageUtil.messagePlayer(commandSender, "&c" + label + " is disabled on this server."); } @Override @@ -115,9 +115,11 @@ private void handleCommand(CommandSender sender, Method key = commandMap.get(cmdLabel).getKey(); Object value = commandMap.get(cmdLabel).getValue(); Command command = key.getAnnotation(Command.class); + String permission = command.permission(); - if (!("").equals(command.permission()) && !sender.hasPermission(command.permission())) { - MessageUtil.messagePlayer(sender, command.noPermission()); + if (!permission.isEmpty() && !sender.hasPermission(permission)) { + String noPermissionMsg = command.noPermission(); + MessageUtil.messagePlayer(sender, noPermissionMsg); return; } @@ -127,8 +129,8 @@ private void handleCommand(CommandSender sender, } try { - key.invoke(value, new CommandArgs(sender, cmd, label, args, - cmdLabel.split("\\.").length - 1)); + String[] split = cmdLabel.split("\\."); + key.invoke(value, new CommandArgs(sender, cmd, label, args, split.length - 1)); } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) { ex.printStackTrace(); } @@ -146,12 +148,14 @@ private void handleCommand(CommandSender sender, */ public void registerCommands(@NotNull Object obj) { for (Method method : obj.getClass().getMethods()) { + String methodName = method.getName(); + if (method.getAnnotation(Command.class) != null) { Command command = method.getAnnotation(Command.class); if (method.getParameterTypes().length > 1 || method.getParameterTypes()[0] != CommandArgs.class) { MessageUtil.log(Level.WARNING, "&cUnable to register command " - + method.getName() + ". Unexpected method arguments" + + methodName + ". Unexpected method arguments" ); continue; } @@ -167,19 +171,20 @@ public void registerCommands(@NotNull Object obj) { if (method.getParameterTypes().length != 1 || method.getParameterTypes()[0] != CommandArgs.class) { MessageUtil.log(Level.WARNING, "Unable to register tab completer " - + method.getName() + ". Unexpected method arguments" + + methodName + ". Unexpected method arguments" ); continue; } if (method.getReturnType() != List.class) { MessageUtil.log(Level.WARNING, "Unable to register tab completer " - + method.getName() + ". Unexpected return type" + + methodName + ". Unexpected return type" ); continue; } - registerCompleter(completer.name(), method, obj); + String completerName = completer.name(); + registerCompleter(completerName, method, obj); for (String alias : completer.aliases()) { registerCompleter(alias, method, obj); @@ -200,22 +205,30 @@ private void registerCommand(@NotNull Command command, @NotNull String label, Method method, Object obj) { - commandMap.put(label.toLowerCase(Locale.ROOT), new AbstractMap.SimpleEntry<>(method, obj)); - commandMap.put(plugin.getName() + ':' + label.toLowerCase(Locale.ROOT), new AbstractMap.SimpleEntry<>(method, obj)); + String pluginName = plugin.getName(); + String lowerCaseLabel = label.toLowerCase(Locale.ROOT); + + commandMap.put(lowerCaseLabel, new AbstractMap.SimpleEntry<>(method, obj)); + commandMap.put(pluginName + ':' + lowerCaseLabel, new AbstractMap.SimpleEntry<>(method, obj)); String cmdLabel = label.replace(".", ",").split(",")[0].toLowerCase(Locale.ROOT); + org.bukkit.command.Command mapCommand = map.getCommand(cmdLabel); - if (map.getCommand(cmdLabel) == null) { + if (mapCommand == null) { org.bukkit.command.Command cmd = new BukkitCommand(cmdLabel, this, plugin); - map.register(plugin.getName(), cmd); + map.register(pluginName, cmd); } - if (!("").equalsIgnoreCase(command.description()) && cmdLabel.equalsIgnoreCase(label)) { - Objects.requireNonNull(map.getCommand(cmdLabel)).setDescription(command.description()); + String description = command.description(); + + if (!description.isEmpty() && cmdLabel.equalsIgnoreCase(label)) { + Objects.requireNonNull(mapCommand).setDescription(description); } - if (!("").equalsIgnoreCase(command.usage()) && cmdLabel.equalsIgnoreCase(label)) { - Objects.requireNonNull(map.getCommand(cmdLabel)).setUsage(command.usage()); + String usage = command.usage(); + + if (!usage.isEmpty() && cmdLabel.equalsIgnoreCase(label)) { + Objects.requireNonNull(mapCommand).setUsage(usage); } } @@ -231,15 +244,18 @@ private void registerCompleter(@NotNull String label, Method method, Object obj) if (map.getCommand(cmdLabel) == null) { org.bukkit.command.Command command = new BukkitCommand(cmdLabel, this, plugin); - map.register(plugin.getName(), command); + String pluginName = plugin.getName(); + map.register(pluginName, command); } + String methodName = method.getName(); + if (map.getCommand(cmdLabel) instanceof BukkitCommand) { BukkitCommand command = (BukkitCommand) map.getCommand(cmdLabel); if (command == null) { MessageUtil.log(Level.WARNING, "&cUnable to register tab completer: " - + method.getName() + ". A command with that name doesn't exist!" + + methodName + ". A command with that name doesn't exist!" ); return; } @@ -256,7 +272,7 @@ private void registerCompleter(@NotNull String label, Method method, Object obj) if (command == null) { MessageUtil.log(Level.WARNING, "&cUnable to register tab completer: " - + method.getName() + ". A command with that name doesn't exist!" + + methodName + ". A command with that name doesn't exist!" ); return; } @@ -275,7 +291,7 @@ private void registerCompleter(@NotNull String label, Method method, Object obj) } else { MessageUtil.log(Level.WARNING, "&cUnable to register tab completer: " - + method.getName() + ". A tab completer is already registered for that command!" + + methodName + ". A tab completer is already registered for that command!" ); } } catch (IllegalAccessException | NoSuchFieldException ex) { diff --git a/src/main/java/net/foulest/pixeladdons/util/yaml/CustomYamlConfiguration.java b/src/main/java/net/foulest/pixeladdons/util/yaml/CustomYamlConfiguration.java index a827418..25bbbc6 100644 --- a/src/main/java/net/foulest/pixeladdons/util/yaml/CustomYamlConfiguration.java +++ b/src/main/java/net/foulest/pixeladdons/util/yaml/CustomYamlConfiguration.java @@ -17,7 +17,6 @@ */ package net.foulest.pixeladdons.util.yaml; -import com.google.common.base.Charsets; import lombok.Cleanup; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; @@ -25,10 +24,12 @@ import org.jetbrains.annotations.Nullable; import java.io.*; +import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; /** * CustomYamlConfiguration is an extension of YamlConfiguration @@ -38,9 +39,17 @@ */ public class CustomYamlConfiguration extends YamlConfiguration { - // Map to store the path of the YAML keys and their associated comments + /** + * Map to store the path of the YAML keys and their associated comments + */ private final Map commentsMap = new LinkedHashMap<>(); + /** + * Loads the CustomYamlConfiguration from a String. + * + * @param contents The YAML data to load. + * @throws InvalidConfigurationException If the configuration is invalid. + */ @Override public void loadFromString(String contents) throws InvalidConfigurationException { super.loadFromString(contents); // Call the original method to load the data @@ -52,13 +61,18 @@ public void loadFromString(String contents) throws InvalidConfigurationException parseAndStoreComments(contents); } + /** + * Saves the CustomYamlConfiguration to a String. + * + * @return The YAML data as a String. + */ @Override public String saveToString() { // Strip all comments from the original data String dataWithoutComments = super.saveToString().trim(); // Use a pattern to match YAML comments and remove them - String dataStrippedOfComments = dataWithoutComments.replaceAll("(?m)^\\s*#.*?$", "").trim(); + String dataStrippedOfComments = dataWithoutComments.replaceAll("(?m)^\\s*#.*$", "").trim(); StringBuilder dataWithComments = new StringBuilder(); @@ -114,33 +128,41 @@ public String saveToString() { return dataWithComments.toString(); } + /** + * Loads a CustomYamlConfiguration from a file. + * + * @param file The file to load the configuration from. + * @throws IOException If an I/O error occurs. + * @throws InvalidConfigurationException If the configuration is invalid. + */ @Override public void load(File file) throws IOException, InvalidConfigurationException { @Cleanup FileInputStream stream = new FileInputStream(file); - @Cleanup InputStreamReader reader = new InputStreamReader(stream, Charsets.UTF_8); + @Cleanup InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); load(reader); } + /** + * Loads a CustomYamlConfiguration from a reader. + * + * @param reader The reader to load the configuration from. + * @throws IOException If an I/O error occurs. + * @throws InvalidConfigurationException If the configuration is invalid. + */ @Override + @SuppressWarnings("RedundantThrows") public void load(Reader reader) throws IOException, InvalidConfigurationException { @Cleanup BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader); - StringBuilder builder = new StringBuilder(); - String line; - - while (true) { - line = input.readLine(); - - if (line == null) { - break; - } - - builder.append(line); - builder.append('\n'); - } - - loadFromString(builder.toString()); + String builder = input.lines().map(line -> line + '\n').collect(Collectors.joining()); + loadFromString(builder); } + /** + * Loads a CustomYamlConfiguration from a file. + * + * @param file The file to load the configuration from. + * @return The loaded CustomYamlConfiguration. + */ public static @NotNull CustomYamlConfiguration loadConfiguration(File file) { CustomYamlConfiguration config = new CustomYamlConfiguration(); @@ -153,6 +175,12 @@ public void load(Reader reader) throws IOException, InvalidConfigurationExceptio return config; } + /** + * Loads a CustomYamlConfiguration from a reader. + * + * @param reader The reader to load the configuration from. + * @return The loaded CustomYamlConfiguration. + */ public static @NotNull CustomYamlConfiguration loadConfiguration(Reader reader) { CustomYamlConfiguration config = new CustomYamlConfiguration(); @@ -189,12 +217,20 @@ private void parseAndStoreComments(@NotNull String contents) { // Define the pattern within this method Pattern keyPattern = Pattern.compile("^\\s*([\\w\\-]+):.*"); - for (String line : lines) { + for (String entry : lines) { + String line = entry; + if (!line.trim().isEmpty() && line.trim().charAt(0) == '#') { if (commentBuilder.length() > 0) { commentBuilder.append("\n"); } - commentBuilder.append(line.trim().substring(1).trim()); // Remove '#' and trim + + // Remove '#' and trim + line = line.trim(); + line = line.replaceFirst("^#", ""); + line = line.trim(); + + commentBuilder.append(line); } else { if (!line.trim().isEmpty() && isHeader) { @@ -221,7 +257,8 @@ private void parseAndStoreComments(@NotNull String contents) { // In case the file ends with comments not associated with a key if (commentBuilder.length() > 0 && !isHeader) { - commentsMap.put("__footer__", commentBuilder.toString()); + String lastComment = commentBuilder.toString(); + commentsMap.put("__footer__", lastComment); } } }