diff --git a/Changelog.txt b/Changelog.txt index 698739102..103344b54 100644 --- a/Changelog.txt +++ b/Changelog.txt @@ -1,6 +1,112 @@ -Version 2.2.007 - Fixed bug where Green Thumb did not replant if seed was in the off hand +Version 2.2.013 + Modified the RNG for dropping non-ore blocks from Blast Mining to yield about 50% of what was destroyed + (API) Deprecated com.gmail.nossr50.mcMMO.getPlaceStore + (API) Added com.gmail.nossr50.mcMMO.getUserBlockTracker + (API) Added com.gmail.nossr50.mcMMO.getChunkManager + (API) Added new methods to com.gmail.nossr50.util.blockmeta.UserBlockTracker for easier readability + (API) Deprecated the old poorly named methods in UserBlockTracker + (Codebase) Cleaned up and organized unit tests relating to UserBlockTracker + NOTES: + Not planning to delete the deprecated methods in UserBlockTracker anytime soon, as nothing has really changed other than the names + +Version 2.2.012 + Fixed a bug where Daze would cause an exception in older game versions (1.20.4 and older) + +Version 2.2.011 + Fixed bug where some potions on older versions (1.20.4 and older) were not brewable (night vision extended, etc) + Improved logging for Alchemy potion look up (see notes) + +NOTES: + Added detailed logging when multiple configured potions match an ItemStack. + This will help identify issues with potion configuration. + +Version 2.2.010 + Fixed being unable to load REGEN potion type on new versions of Paper/Spigot 1.20.6 + Fixed some potions not gaining XP when brewed (Level 2 potions, etc) + BrewingStands will now remember who owns them, this persists across restarts (see notes) + Fixed rare NPE in mcMMO events when player data was unable to be retrieved + Fixed a NPE that could happen when damaging armor with Axes + Fixed a bug where Alchemy brewing would be cancelled if the player died + (API) Added getMcMMOPlayer() to McMMOPlayerSkillEvent + (API) Added new ctor McMMOPlayerSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType) + (API) Deprecated ctor McMMOPlayerSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added ctor McMMOPlayerAbilityEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerAbilityEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerAbilityActivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added ctor McMMOPlayerAbilityActivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerCatalysisEvent(org.bukkit.entity.Player, double) + (API) Added ctor McMMOPlayerCatalysisEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, double) + (API) Deprecated util method EventUtils.callPlayerAbilityActivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added util method EventUtils.callPlayerAbilityActivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated ctor McMMOPlayerFishingEvent(org.bukkit.entity.Player) + (API) Added ctor McMMOPlayerFishingEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer) + (API) Deprecated ctor McMMOPlayerFishingTreasureEvent.McMMOPlayerFishingTreasureEvent(org.bukkit.entity.Player, org.bukkit.inventory.ItemStack, int) + (API) Added ctor McMMOPlayerFishingTreasureEvent.McMMOPlayerFishingTreasureEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, org.bukkit.inventory.ItemStack, int) + (API) Deprecated ctor McMMOPlayerMagicHunterEvent(org.bukkit.entity.Player, org.bukkit.inventory.ItemStack, int, java.util.Map) + (API) Added ctor McMMOPlayerMagicHunterEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, org.bukkit.inventory.ItemStack, int, java.util.Map) + (API) Deprecated ctor McMMOPlayerAbilityDeactivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Added ctor McMMOPlayerAbilityDeactivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.PrimarySkillType) + (API) Deprecated util method EventUtils.callAbilityDeactivateEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SuperAbilityType) + (API) Added util method EventUtils.callAbilityDeactivateEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SuperAbilityType) + (API) Deprecated util EventUtils.callSubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Added util EventUtils.callSubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Deprecated ctor SubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Added ctor SubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SubSkillType) + (API) Deprecated ctor SubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.SubSkillType, double) + (API) Added ctor SubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.SubSkillType, double) + (API) Deprecated ctor SubSkillEvent(org.bukkit.entity.Player, com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill) + (API) Added ctor SubSkillEvent(com.gmail.nossr50.datatypes.player.McMMOPlayer, com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill) + (API) Deprecated ctor AlchemyBrewCheckTask(org.bukkit.entity.Player, org.bukkit.block.BrewingStand) + (API) Added ctor AlchemyBrewCheckTask(org.bukkit.block.BrewingStand) + + NOTES: + You can now use hoppers and brewing stands and not have to worry about having to re-interact with the brewing stand over and over again + Ownership of a brewing stand is whoever last interacted with it, this persists across restarts + This is not an exhaustive list of API changes in this update, but most of the important ones should be documented here. + +Version 2.2.009 + Fixed a bug that prevented mcMMO from loading on MC versions older than 1.20.6 + Dramatically increased the base XP for Alchemy again (see notes) + + NOTES: + Alchemy leveling still felt too slow, so I've increased it again. You can either delete experience.yml to get the new values or adjust them manually. + If you haven't updated mcMMO since 2.2.006 or older you don't need to do anything to get these new values. + The new default values are... + Potion_Brewing: + Stage_1: 666 + Stage_2: 1111 + Stage_3: 1750 + Stage_4: 2250 + +Version 2.2.008 + Fixed alchemy potions not upgrading correctly (This will only affect new potions made, see notes) + Fixed a bug where alchemy potions had italicized names + Fixed a bug where messages were not being sent to the action bar in 1.20.6 + (SQL) Fixed bug that broke /mccooldowns and /archery in some circumstances + Fixed some exceptions that could happen with parties disabled (thanks IAISI) + + NOTES: + mcMMO-exclusive Potions (haste, etc) made on version 2.2.007 of mcMMO will not upgrade correctly, you'll just have to make new ones. Sorry for the inconvenience. + Alchemy potions will now be brewed as type "Mundane" behind the scenes, this used to be Uncraftable/Water. This led to some issues. So I've changed it to be Mundane. + +Version 2.2.007 + Compatibility with the 1.20.5 / 1.20.6 MC Update + Fixed bug where Alchemy was not brewing certain potions (haste, etc) + Tree Feller no longer restricts how many saplings can drop + Tree Feller now drops leaves 25% of the time (up from 10%) + Alchemy XP has been DRAMATICALLY increased, it was extremely grindy by default + Alchemy experience values in experience.yml are now found under 'Experience_Values.Alchemy.Potion_Brewing' + Fixed bug where the probability of success of Graceful Roll was not being calculated correctly + Fixed bug where Green Thumb did not replant if seed was in the off hand + Added armadillo to combat experience in experience.yml + + NOTES: + While fixing various Alchemy bugs, I noticed Alchemy leveled SUPER slow, I have increased it dramatically. Feel free to change it back by modifying the new values in experience.yml + I did my best to keep mcMMO compatible with older versions of Minecraft for this update. + This update to MC was quite large, with breaking changes to a lot of code relating to Alchemy, and some other things. + I expect there to be bugs, please report them on GitHub or Discord, but preferably GitHub. + I will be working on fixing these bugs as they come in, so please be patient. Version 2.2.006 Added new config custom_item_support.yml Added support for hex color codes in the locale file, uses the format &#RRGGBB (see notes) diff --git a/pom.xml b/pom.xml index 9bdddf369..c0de518e0 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 com.gmail.nossr50.mcMMO mcMMO - 2.2.007-SNAPSHOT + 2.2.013-SNAPSHOT mcMMO https://github.com/mcMMO-Dev/mcMMO @@ -75,16 +75,17 @@ maven-surefire-plugin - 3.0.0-M7 + 3.2.5 org.junit.jupiter:junit-jupiter false + skip maven-failsafe-plugin - 3.0.0-M7 + 3.2.5 org.junit.jupiter:junit-jupiter @@ -95,12 +96,12 @@ org.apache.maven.plugins maven-release-plugin - 3.0.0-M6 + 3.0.1 org.apache.maven.plugins maven-compiler-plugin - 3.10.1 + 3.13.0 17 @@ -112,6 +113,7 @@ maven-assembly-plugin + 3.7.1 src/main/assembly/package.xml @@ -130,7 +132,7 @@ org.apache.maven.plugins maven-shade-plugin - 3.3.0 + 3.5.3 @@ -140,23 +142,22 @@ org.bstats:bstats-base org.bstats:bstats-bukkit net.kyori:adventure-api - net.kyori:adventure-text-serializer-gson - net.kyori:adventure-platform-bukkit - net.kyori:adventure-platform-api - net.kyori:adventure-platform-viaversion - net.kyori:adventure-platform-facet - net.kyori:adventure-nbt net.kyori:adventure-key + net.kyori:adventure-nbt + net.kyori:adventure-platform-api + net.kyori:adventure-platform-bukkit + net.kyori:adventure-platform-facet + net.kyori:adventure-platform-viaversion + net.kyori:adventure-text-serializer-bungeecord + net.kyori:adventure-text-serializer-gson + net.kyori:adventure-text-serializer-gson-legacy-impl + net.kyori:adventure-text-serializer-json + net.kyori:adventure-text-serializer-json-legacy-impl + net.kyori:adventure-text-serializer-legacy net.kyori:examination-api net.kyori:examination-string - net.kyori:adventure-text-serializer-legacy - net.kyori:adventure-text-serializer-gson - net.kyori:adventure-text-serializer-json - net.kyori:adventure-text-serializer-bungeecord - net.kyori:adventure-text-serializer-craftbukkit - net.kyori:adventure-text-serializer-gson-legacy-impl - net.kyori:adventure-text-serializer-json-legacy-impl net.kyori:option + net.kyori:adventure-text-serializer-craftbukkit co.aikar:acf-bukkit com.tcoded:FoliaLib @@ -222,6 +223,11 @@ + + + dmulloy2-repo + https://repo.dmulloy2.net/repository/public/ + spigot-repo https://hub.spigotmc.org/nexus/content/repositories/snapshots/ @@ -254,8 +260,11 @@ devmart-other https://nexuslite.gcnt.net/repos/other/ - - + + + papermc + https://repo.papermc.io/repository/maven-public/ + @@ -265,6 +274,12 @@ 3.25.3 test + + com.comphenix.protocol + ProtocolLib + LATEST + compile + com.h2database h2 @@ -290,57 +305,57 @@ net.kyori adventure-text-serializer-gson - 4.15.0 + 4.17.0 net.kyori adventure-text-serializer-gson-legacy-impl - 4.15.0 + 4.17.0 net.kyori adventure-text-serializer-json - 4.15.0 + 4.17.0 net.kyori adventure-text-serializer-json-legacy-impl - 4.15.0 + 4.17.0 net.kyori adventure-api - 4.15.0 + 4.17.0 net.kyori adventure-nbt - 4.15.0 + 4.17.0 net.kyori adventure-key - 4.15.0 + 4.17.0 net.kyori adventure-platform-api - 4.3.2 + 4.3.3-SNAPSHOT net.kyori adventure-platform-bukkit - 4.3.2 + LATEST net.kyori adventure-platform-facet - 4.3.2 + 4.3.3-SNAPSHOT net.kyori adventure-platform-viaversion - 4.3.2 + 4.3.3-SNAPSHOT net.kyori @@ -350,18 +365,18 @@ org.apache.maven.scm maven-scm-provider-gitexe - 2.0.0-M1 + 2.1.0 org.bstats bstats-bukkit - 3.0.0 + 3.0.2 compile org.spigotmc spigot-api - 1.20.4-R0.1-SNAPSHOT + 1.20.6-R0.1-SNAPSHOT provided @@ -397,36 +412,36 @@ org.junit.jupiter junit-jupiter - 5.9.0 + 5.11.0-M2 test org.mockito mockito-core - 4.6.1 + 5.12.0 test org.mockito mockito-inline - 4.6.1 + 5.2.0 test org.apache.tomcat tomcat-jdbc - 10.1.0-M17 + 10.1.24 compile org.jetbrains annotations - 23.0.0 + 24.1.0 com.google.guava guava - 32.1.1-jre + 33.2.0-jre compile @@ -435,5 +450,29 @@ 0.3.1 compile + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java index 3ad6d43e7..1597fbb20 100644 --- a/src/main/java/com/gmail/nossr50/api/AbilityAPI.java +++ b/src/main/java/com/gmail/nossr50/api/AbilityAPI.java @@ -83,8 +83,8 @@ public final class AbilityAPI { } public static boolean isBleeding(LivingEntity entity) { - if(entity.isValid()) { - if(entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (entity.isValid()) { + if (entity.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { return true; } } diff --git a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java index c626810ec..a32873a29 100644 --- a/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java +++ b/src/main/java/com/gmail/nossr50/api/ExperienceAPI.java @@ -516,7 +516,7 @@ public final class ExperienceAPI { } public static float getOfflineXPRaw(@NotNull OfflinePlayer offlinePlayer, @NotNull PrimarySkillType skillType) throws InvalidPlayerException, UnsupportedOperationException { - if(SkillTools.isChildSkill(skillType)) + if (SkillTools.isChildSkill(skillType)) throw new UnsupportedOperationException(); return getOfflineProfile(offlinePlayer).getSkillXpLevelRaw(skillType); @@ -1143,14 +1143,10 @@ public final class ExperienceAPI { * @param blockStates the blocks to reward XP for * @param mcMMOPlayer the target player */ - public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) - { - for(BlockState bs : blockStates) - { - for(PrimarySkillType skillType : PrimarySkillType.values()) - { - if(ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) - { + public static void addXpFromBlocks(ArrayList blockStates, McMMOPlayer mcMMOPlayer) { + for(BlockState bs : blockStates) { + for(PrimarySkillType skillType : PrimarySkillType.values()) { + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1163,12 +1159,9 @@ public final class ExperienceAPI { * @param mcMMOPlayer the target player * @param skillType target primary skill */ - public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) - { - for(BlockState bs : blockStates) - { - if(ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) - { + public static void addXpFromBlocksBySkill(ArrayList blockStates, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + for(BlockState bs : blockStates) { + if (ExperienceConfig.getInstance().getXp(skillType, bs.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, bs.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1179,12 +1172,9 @@ public final class ExperienceAPI { * @param blockState The target blockstate * @param mcMMOPlayer The target player */ - public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) - { - for(PrimarySkillType skillType : PrimarySkillType.values()) - { - if(ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) - { + public static void addXpFromBlock(BlockState blockState, McMMOPlayer mcMMOPlayer) { + for(PrimarySkillType skillType : PrimarySkillType.values()) { + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } } @@ -1196,10 +1186,8 @@ public final class ExperienceAPI { * @param mcMMOPlayer The target player * @param skillType target primary skill */ - public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) - { - if(ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) - { + public static void addXpFromBlockBySkill(BlockState blockState, McMMOPlayer mcMMOPlayer, PrimarySkillType skillType) { + if (ExperienceConfig.getInstance().getXp(skillType, blockState.getType()) > 0) { mcMMOPlayer.applyXpGain(skillType, ExperienceConfig.getInstance().getXp(skillType, blockState.getType()), XPGainReason.PVE, XPGainSource.SELF); } } diff --git a/src/main/java/com/gmail/nossr50/api/PartyAPI.java b/src/main/java/com/gmail/nossr50/api/PartyAPI.java index e86bf4619..f18dcf6fe 100644 --- a/src/main/java/com/gmail/nossr50/api/PartyAPI.java +++ b/src/main/java/com/gmail/nossr50/api/PartyAPI.java @@ -50,7 +50,7 @@ public final class PartyAPI { * @return true if the player is in a party, false otherwise */ public static boolean inParty(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) return false; return UserManager.getPlayer(player).inParty(); @@ -94,14 +94,14 @@ public final class PartyAPI { */ @Deprecated public static void addToParty(Player player, String partyName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) { + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return; } //Check if player profile is loaded final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) + if (mmoPlayer == null) return; Party party = mcMMO.p.getPartyManager().getParty(partyName); @@ -109,8 +109,7 @@ public final class PartyAPI { if (party == null) { party = new Party(new PartyLeader(player.getUniqueId(), player.getName()), partyName); } else { - if(mcMMO.p.getPartyManager().isPartyFull(player, party)) - { + if (mcMMO.p.getPartyManager().isPartyFull(player, party)) { NotificationManager.sendPlayerInformation(player, NotificationType.PARTY_MESSAGE, "Commands.Party.PartyFull", party.toString()); return; } @@ -124,8 +123,7 @@ public final class PartyAPI { * 0 or less for no size limit * @return the max party size on this server */ - public static int getMaxPartySize() - { + public static int getMaxPartySize() { return mcMMO.p.getGeneralConfig().getPartyMaxSize(); } @@ -140,7 +138,7 @@ public final class PartyAPI { */ public static void addToParty(Player player, String partyName, boolean bypassLimit) { //Check if player profile is loaded - if(!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) return; Party party = mcMMO.p.getPartyManager().getParty(partyName); @@ -161,7 +159,7 @@ public final class PartyAPI { */ public static void removeFromParty(Player player) { //Check if player profile is loaded - if(!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) + if (!mcMMO.p.getPartyConfig().isPartyEnabled() || UserManager.getPlayer(player) == null) return; mcMMO.p.getPartyManager().removeFromParty(UserManager.getPlayer(player)); @@ -176,7 +174,7 @@ public final class PartyAPI { * @return the leader of the party */ public static @Nullable String getPartyLeader(String partyName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return mcMMO.p.getPartyManager().getPartyLeaderName(partyName); @@ -192,7 +190,7 @@ public final class PartyAPI { */ @Deprecated public static void setPartyLeader(String partyName, String playerName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return; mcMMO.p.getPartyManager().setPartyLeader(mcMMO.p.getServer().getOfflinePlayer(playerName).getUniqueId(), mcMMO.p.getPartyManager().getParty(partyName)); @@ -208,7 +206,7 @@ public final class PartyAPI { */ @Deprecated public static List getOnlineAndOfflineMembers(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) { + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) { return null; } @@ -230,7 +228,7 @@ public final class PartyAPI { */ @Deprecated public static LinkedHashSet getMembers(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return (LinkedHashSet) mcMMO.p.getPartyManager().getAllMembers(player).values(); @@ -245,7 +243,7 @@ public final class PartyAPI { * @return all the player names and uuids in the player's party */ public static LinkedHashMap getMembersMap(Player player) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return mcMMO.p.getPartyManager().getAllMembers(player); @@ -260,7 +258,7 @@ public final class PartyAPI { * @return all online players in this party */ public static List getOnlineMembers(String partyName) { - if(!mcMMO.p.getPartyConfig().isPartyEnabled()) + if (!mcMMO.p.getPartyConfig().isPartyEnabled()) return null; return mcMMO.p.getPartyManager().getOnlineMembers(partyName); diff --git a/src/main/java/com/gmail/nossr50/chat/ChatManager.java b/src/main/java/com/gmail/nossr50/chat/ChatManager.java index 658f4dd16..0d7c21c65 100644 --- a/src/main/java/com/gmail/nossr50/chat/ChatManager.java +++ b/src/main/java/com/gmail/nossr50/chat/ChatManager.java @@ -125,7 +125,7 @@ public class ChatManager { * @param targetChatChannel target chat channel */ public void setOrToggleChatChannel(@NotNull McMMOPlayer mmoPlayer, @NotNull ChatChannel targetChatChannel) { - if(targetChatChannel == mmoPlayer.getChatChannel()) { + if (targetChatChannel == mmoPlayer.getChatChannel()) { //Disabled message mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Chat.Channel.Off", StringUtils.getCapitalized(targetChatChannel.toString()))); mmoPlayer.setChatMode(ChatChannel.NONE); @@ -144,7 +144,7 @@ public class ChatManager { StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < args.length; i++) { - if(i + 1 >= args.length) { + if (i + 1 >= args.length) { stringBuilder.append(args[i]); } else { stringBuilder.append(args[i]).append(" "); @@ -162,12 +162,12 @@ public class ChatManager { public boolean isMessageAllowed(@NotNull McMMOPlayer mmoPlayer) { switch (mmoPlayer.getChatChannel()) { case ADMIN: - if(mmoPlayer.getPlayer().isOp() || Permissions.adminChat(mmoPlayer.getPlayer())) { + if (mmoPlayer.getPlayer().isOp() || Permissions.adminChat(mmoPlayer.getPlayer())) { return true; } break; case PARTY: - if(mmoPlayer.getParty() != null && Permissions.partyChat(mmoPlayer.getPlayer())) { + if (mmoPlayer.getParty() != null && Permissions.partyChat(mmoPlayer.getPlayer())) { return true; } break; @@ -206,7 +206,7 @@ public class ChatManager { * @return true if the chat channel is enabled */ public boolean isChatChannelEnabled(@NotNull ChatChannel chatChannel) { - if(!isChatEnabled) { + if (!isChatEnabled) { return false; } else { switch(chatChannel) { diff --git a/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java b/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java index 226eab83d..318460222 100644 --- a/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java +++ b/src/main/java/com/gmail/nossr50/chat/SamePartyPredicate.java @@ -20,12 +20,12 @@ public class SamePartyPredicate implements Predicate @Override public boolean test(T t) { //Include the console in the audience - if(t instanceof ConsoleCommandSender) { + if (t instanceof ConsoleCommandSender) { return false; //Party audiences are special, we exclude console from them to avoid double messaging since we send a more verbose version to consoles } else { - if(t instanceof Player player) { + if (t instanceof Player player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer != null) { + if (mcMMOPlayer != null) { return mcMMOPlayer.getParty() == party; } } diff --git a/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java b/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java index eb606af6d..2b9344f51 100644 --- a/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java +++ b/src/main/java/com/gmail/nossr50/chat/author/AbstractPlayerAuthor.java @@ -48,15 +48,15 @@ public abstract class AbstractPlayerAuthor implements Author { */ protected @NotNull String getSanitizedName(@NotNull ChatChannel chatChannel, boolean useDisplayName) { //Already in cache - if(sanitizedNameCache.containsKey(chatChannel)) { + if (sanitizedNameCache.containsKey(chatChannel)) { //Update cache - if(useDisplayName && hasPlayerDisplayNameChanged()) { + if (useDisplayName && hasPlayerDisplayNameChanged()) { updateLastKnownDisplayName(); updateSanitizedNameCache(chatChannel, true); } } else { //Update last known display name - if(useDisplayName && hasPlayerDisplayNameChanged()) { + if (useDisplayName && hasPlayerDisplayNameChanged()) { updateLastKnownDisplayName(); } @@ -76,7 +76,7 @@ public abstract class AbstractPlayerAuthor implements Author { * @param useDisplayName whether to use this authors display name */ private void updateSanitizedNameCache(@NotNull ChatChannel chatChannel, boolean useDisplayName) { - if(useDisplayName) { + if (useDisplayName) { sanitizedNameCache.put(chatChannel, TextUtils.sanitizeForSerializer(player.getDisplayName())); } else { //No need to sanitize a basic String diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java index 5ec0f5c37..96c7ad1a6 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/AdminChatMailer.java @@ -57,7 +57,7 @@ public class AdminChatMailer extends AbstractChatMailer { * @return the styled string, based on a locale entry */ public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, boolean canColor) { - if(canColor) { + if (canColor) { return LocaleLoader.getTextComponent("Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), message); } else { return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Admin", author.getAuthoredName(ChatChannel.ADMIN), message)); @@ -83,7 +83,7 @@ public class AdminChatMailer extends AbstractChatMailer { McMMOChatEvent chatEvent = new McMMOAdminChatEvent(pluginRef, chatMessage, isAsync); Bukkit.getPluginManager().callEvent(chatEvent); - if(!chatEvent.isCancelled()) { + if (!chatEvent.isCancelled()) { sendMail(chatMessage); } } diff --git a/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java b/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java index ad8d8992d..e4edb0320 100644 --- a/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java +++ b/src/main/java/com/gmail/nossr50/chat/mailer/PartyChatMailer.java @@ -36,7 +36,7 @@ public class PartyChatMailer extends AbstractChatMailer { McMMOChatEvent chatEvent = new McMMOPartyChatEvent(pluginRef, chatMessage, party, isAsync); Bukkit.getPluginManager().callEvent(chatEvent); - if(!chatEvent.isCancelled()) { + if (!chatEvent.isCancelled()) { sendMail(chatMessage); } } @@ -60,14 +60,14 @@ public class PartyChatMailer extends AbstractChatMailer { * @return the styled string, based on a locale entry */ public @NotNull TextComponent addStyle(@NotNull Author author, @NotNull String message, boolean canColor, boolean isLeader) { - if(canColor) { - if(isLeader) { + if (canColor) { + if (isLeader) { return LocaleLoader.getTextComponent("Chat.Style.Party.Leader", author.getAuthoredName(ChatChannel.PARTY), message); } else { return LocaleLoader.getTextComponent("Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), message); } } else { - if(isLeader) { + if (isLeader) { return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Party.Leader", author.getAuthoredName(ChatChannel.PARTY), message)); } else { return TextUtils.ofLegacyTextRaw(LocaleLoader.getString("Chat.Style.Party", author.getAuthoredName(ChatChannel.PARTY), message)); diff --git a/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java b/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java index 756c3d457..02b2499ea 100644 --- a/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java +++ b/src/main/java/com/gmail/nossr50/chat/message/PartyChatMessage.java @@ -52,7 +52,7 @@ public class PartyChatMessage extends AbstractChatMessage { messagePartyChatSpies(spyMessage); //Console message - if(ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.PARTY)) + if (ChatConfig.getInstance().isConsoleIncludedInAudience(ChatChannel.PARTY)) mcMMO.p.getChatManager().sendConsoleMessage(author, spyMessage); } @@ -67,11 +67,11 @@ public class PartyChatMessage extends AbstractChatMessage { Player player = mcMMOPlayer.getPlayer(); //Check for toggled players - if(mcMMOPlayer.isPartyChatSpying()) { + if (mcMMOPlayer.isPartyChatSpying()) { Party adminParty = mcMMOPlayer.getParty(); //Only message admins not part of this party - if(adminParty == null || adminParty != getParty()) { + if (adminParty == null || adminParty != getParty()) { //TODO: Hacky, rewrite later Audience audience = mcMMO.getAudiences().player(player); audience.sendMessage(spyMessage); diff --git a/src/main/java/com/gmail/nossr50/commands/CommandManager.java b/src/main/java/com/gmail/nossr50/commands/CommandManager.java index 3b9d8516e..d870baed0 100644 --- a/src/main/java/com/gmail/nossr50/commands/CommandManager.java +++ b/src/main/java/com/gmail/nossr50/commands/CommandManager.java @@ -47,7 +47,7 @@ public class CommandManager { } private void registerSkillCommands() { - if(mcMMO.p.getGeneralConfig().isMasterySystemEnabled()) { + if (mcMMO.p.getGeneralConfig().isMasterySystemEnabled()) { bukkitCommandManager.registerCommand(new PowerLevelCommand(pluginRef)); } } @@ -56,11 +56,11 @@ public class CommandManager { * Registers chat commands if the chat system is enabled */ private void registerChatCommands() { - if(ChatConfig.getInstance().isChatEnabled()) { - if(ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.ADMIN)) { + if (ChatConfig.getInstance().isChatEnabled()) { + if (ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.ADMIN)) { bukkitCommandManager.registerCommand(new AdminChatCommand(pluginRef)); } - if(pluginRef.getPartyConfig().isPartyEnabled() && ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.PARTY)) { + if (pluginRef.getPartyConfig().isPartyEnabled() && ChatConfig.getInstance().isChatChannelEnabled(ChatChannel.PARTY)) { bukkitCommandManager.registerCommand(new PartyChatCommand(pluginRef)); } } @@ -75,7 +75,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(POWER_LEVEL_CONDITION, (context) -> { BukkitCommandIssuer issuer = context.getIssuer(); - if(issuer.getIssuer() instanceof Player) { + if (issuer.getIssuer() instanceof Player) { validateLoadedData(issuer.getPlayer()); } else { throw new ConditionFailedException(LocaleLoader.getString("Commands.NoConsole")); @@ -88,7 +88,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(ADMIN_CONDITION, (context) -> { BukkitCommandIssuer issuer = context.getIssuer(); - if(issuer.getIssuer() instanceof Player) { + if (issuer.getIssuer() instanceof Player) { validateLoadedData(issuer.getPlayer()); validateAdmin(issuer.getPlayer()); } @@ -97,7 +97,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(MMO_DATA_LOADED, (context) -> { BukkitCommandIssuer bukkitCommandIssuer = context.getIssuer(); - if(bukkitCommandIssuer.getIssuer() instanceof Player) { + if (bukkitCommandIssuer.getIssuer() instanceof Player) { validateLoadedData(bukkitCommandIssuer.getPlayer()); } }); @@ -105,7 +105,7 @@ public class CommandManager { bukkitCommandManager.getCommandConditions().addCondition(PARTY_CONDITION, (context) -> { BukkitCommandIssuer bukkitCommandIssuer = context.getIssuer(); - if(bukkitCommandIssuer.getIssuer() instanceof Player) { + if (bukkitCommandIssuer.getIssuer() instanceof Player) { validateLoadedData(bukkitCommandIssuer.getPlayer()); validatePlayerParty(bukkitCommandIssuer.getPlayer()); //TODO: Is there even a point in validating permission? look into this later @@ -115,20 +115,20 @@ public class CommandManager { } private void validatePermission(@NotNull String permissionNode, @NotNull Permissible permissible) { - if(!permissible.hasPermission(permissionNode)) { + if (!permissible.hasPermission(permissionNode)) { throw new ConditionFailedException(LocaleLoader.getString("mcMMO.NoPermission")); } } public void validateAdmin(@NotNull Player player) { - if(!player.isOp() && !Permissions.adminChat(player)) { + if (!player.isOp() && !Permissions.adminChat(player)) { throw new ConditionFailedException("You are lacking the correct permissions to use this command."); } } public void validateLoadedData(@NotNull Player player) { - if(UserManager.getPlayer(player) == null) { + if (UserManager.getPlayer(player) == null) { throw new ConditionFailedException(LocaleLoader.getString("Profile.PendingLoad")); } } @@ -136,7 +136,7 @@ public class CommandManager { public void validatePlayerParty(@NotNull Player player) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(!pluginRef.getPartyConfig().isPartyEnabled() || mmoPlayer.getParty() == null) { + if (!pluginRef.getPartyConfig().isPartyEnabled() || mmoPlayer.getParty() == null) { throw new ConditionFailedException(LocaleLoader.getString("Commands.Party.None")); } } diff --git a/src/main/java/com/gmail/nossr50/commands/McImportCommand.java b/src/main/java/com/gmail/nossr50/commands/McImportCommand.java index 3c913ea47..d19247d0d 100644 --- a/src/main/java/com/gmail/nossr50/commands/McImportCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McImportCommand.java @@ -200,14 +200,11 @@ public class McImportCommand implements CommandExecutor { String skillName = "UNIDENTIFIED"; if (materialName.contains("ORE")) { skillName = "Mining"; - } - else if (materialName.contains("LOG") || materialName.contains("LEAVES")) { + } else if (materialName.contains("LOG") || materialName.contains("LEAVES")) { skillName = "Woodcutting"; - } - else if (materialName.contains("GRASS") || materialName.contains("SHORT_GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) { + } else if (materialName.contains("GRASS") || materialName.contains("SHORT_GRASS") || materialName.contains("FLOWER") || materialName.contains("CROP")) { skillName = "Herbalism"; - } - else if (materialName.contains("DIRT") || materialName.contains("SAND")) { + } else if (materialName.contains("DIRT") || materialName.contains("SAND")) { skillName = "Excavation"; } @@ -222,8 +219,7 @@ public class McImportCommand implements CommandExecutor { if (skillName.equals("Mining")) { skillContents.add(" " + " " + "Smelting_XP_Gain: 9"); - } - else if (skillName.equals("Woodcutting")) { + } else if (skillName.equals("Woodcutting")) { skillContents.add(" " + " " + "Is_Log: " + materialName.contains("LOG")); } } @@ -239,20 +235,15 @@ public class McImportCommand implements CommandExecutor { String toolType = "UNIDENTIFIED"; if (materialName.contains("PICKAXE")) { toolType = "Pickaxes"; - } - else if (materialName.contains("AXE")) { + } else if (materialName.contains("AXE")) { toolType = "Axes"; - } - else if (materialName.contains("BOW")) { + } else if (materialName.contains("BOW")) { toolType = "Bows"; - } - else if (materialName.contains("HOE")) { + } else if (materialName.contains("HOE")) { toolType = "Hoes"; - } - else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) { + } else if (materialName.contains("SHOVEL") || materialName.contains("SPADE")) { toolType = "Shovels"; - } - else if (materialName.contains("SWORD")) { + } else if (materialName.contains("SWORD")) { toolType = "Swords"; } @@ -279,14 +270,11 @@ public class McImportCommand implements CommandExecutor { String toolType = "UNIDENTIFIED"; if (materialName.contains("BOOT") || materialName.contains("SHOE")) { toolType = "Boots"; - } - else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) { + } else if (materialName.contains("CHESTPLATE") || materialName.contains("CHEST")) { toolType = "Chestplates"; - } - else if (materialName.contains("HELM") || materialName.contains("HAT")) { + } else if (materialName.contains("HELM") || materialName.contains("HAT")) { toolType = "Helmets"; - } - else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) { + } else if (materialName.contains("LEGGINGS") || materialName.contains("LEGS") || materialName.contains("PANTS")) { toolType = "Leggings"; } diff --git a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java index 838722131..3d683b800 100644 --- a/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McmmoCommand.java @@ -72,7 +72,7 @@ public class McmmoCommand implements CommandExecutor { private void displayOtherCommands(CommandSender sender) { //Don't show them this category if they have none of the permissions - if(!Permissions.skillreset(sender) && !Permissions.mmoedit(sender) && !Permissions.adminChat(sender) && !Permissions.mcgod(sender)) + if (!Permissions.skillreset(sender) && !Permissions.mmoedit(sender) && !Permissions.adminChat(sender) && !Permissions.mcgod(sender)) return; sender.sendMessage(LocaleLoader.getString("Commands.Other")); diff --git a/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java b/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java index ff5b4ab2d..8bcdde1ad 100644 --- a/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/McscoreboardCommand.java @@ -23,12 +23,12 @@ public class McscoreboardCommand implements TabExecutor { return true; } - if(!mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + if (!mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { sender.sendMessage(LocaleLoader.getString("Scoreboard.Disabled")); return true; } - if(!ScoreboardManager.isPlayerBoardSetup(sender.getName())) { + if (!ScoreboardManager.isPlayerBoardSetup(sender.getName())) { sender.sendMessage(LocaleLoader.getString("Scoreboard.NotSetupYet")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java index f5ad2641c..2eb487826 100644 --- a/src/main/java/com/gmail/nossr50/commands/XprateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/XprateCommand.java @@ -37,16 +37,14 @@ public class XprateCommand implements TabExecutor { if (mcMMO.p.isXPEventEnabled()) { - if(mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) - { + if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Stop"), LocaleLoader.getString("Commands.Event.Stop.Subtitle"), 10, 10*20, 20); } - if(mcMMO.p.getGeneralConfig().broadcastEventMessages()) - { + if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Stop.Subtitle")); } @@ -72,34 +70,29 @@ public class XprateCommand implements TabExecutor { if (CommandUtils.shouldDisableToggle(args[1])) { mcMMO.p.setXPEventEnabled(false); - } - else if (CommandUtils.shouldEnableToggle(args[1])) { + } else if (CommandUtils.shouldEnableToggle(args[1])) { mcMMO.p.setXPEventEnabled(true); - } - else { + } else { return false; } int newXpRate = Integer.parseInt(args[0]); - if(newXpRate < 0) - { + if (newXpRate < 0) { sender.sendMessage(ChatColor.RED+LocaleLoader.getString("Commands.NegativeNumberWarn")); return true; } ExperienceConfig.getInstance().setExperienceGainsGlobalMultiplier(newXpRate); - if(mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) - { + if (mcMMO.p.getAdvancedConfig().useTitlesForXPEvent()) { NotificationManager.broadcastTitle(mcMMO.p.getServer(), LocaleLoader.getString("Commands.Event.Start"), LocaleLoader.getString("Commands.Event.XP", newXpRate), 10, 10*20, 20); } - if(mcMMO.p.getGeneralConfig().broadcastEventMessages()) - { + if (mcMMO.p.getGeneralConfig().broadcastEventMessages()) { mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.Start")); mcMMO.p.getServer().broadcastMessage(LocaleLoader.getString("Commands.Event.XP", newXpRate)); } diff --git a/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java index 5a60d9bee..e793a60f8 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/DropTreasureCommand.java @@ -17,8 +17,8 @@ //public class DropTreasureCommand implements CommandExecutor { // @Override // public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { -// if(sender instanceof Player) { -// if(!sender.isOp()) { +// if (sender instanceof Player) { +// if (!sender.isOp()) { // sender.sendMessage("This command is for Operators only"); // return false; // } @@ -27,13 +27,13 @@ // Location location = player.getLocation(); // McMMOPlayer mmoPlayer = UserManager.getPlayer(player); // -// if(mmoPlayer == null) { +// if (mmoPlayer == null) { // //TODO: Localize // player.sendMessage("Your player data is not loaded yet"); // return false; // } // -// if(args.length == 0) { +// if (args.length == 0) { // mcMMO.p.getLogger().info(player.toString() +" is dropping all mcMMO treasures via admin command at location "+location.toString()); // for(Rarity rarity : FishingTreasureConfig.getInstance().fishingRewards.keySet()) { // for(FishingTreasure fishingTreasure : FishingTreasureConfig.getInstance().fishingRewards.get(rarity)) { diff --git a/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java b/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java index 25a87ceb3..767d544f6 100644 --- a/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/admin/PlayerDebugCommand.java @@ -13,7 +13,7 @@ public class PlayerDebugCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(sender instanceof Player) { + if (sender instanceof Player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender); mcMMOPlayer.toggleDebugMode(); //Toggle debug mode NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.Mmodebug.Toggle", String.valueOf(mcMMOPlayer.isDebugMode())); diff --git a/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java index 3c6f93d11..2e71b238d 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/AdminChatCommand.java @@ -25,9 +25,9 @@ public class AdminChatCommand extends BaseCommand { @Default @Conditions(CommandManager.ADMIN_CONDITION) public void processCommand(String[] args) { BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); - if(args == null || args.length == 0) { + if (args == null || args.length == 0) { //Process with no arguments - if(bukkitCommandIssuer.isPlayer()) { + if (bukkitCommandIssuer.isPlayer()) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); pluginRef.getChatManager().setOrToggleChatChannel(mmoPlayer, ChatChannel.ADMIN); } else { @@ -35,10 +35,10 @@ public class AdminChatCommand extends BaseCommand { mcMMO.p.getLogger().info("You cannot switch chat channels as console, please provide full arguments."); } } else { - if(bukkitCommandIssuer.isPlayer()) { + if (bukkitCommandIssuer.isPlayer()) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); - if(mmoPlayer == null) + if (mmoPlayer == null) return; //Message contains the original command so it needs to be passed to this method to trim it diff --git a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java index cfdbc61d8..369b4a58b 100644 --- a/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/chat/PartyChatCommand.java @@ -30,9 +30,9 @@ public class PartyChatCommand extends BaseCommand { public void processCommand(String[] args) { BukkitCommandIssuer bukkitCommandIssuer = (BukkitCommandIssuer) getCurrentCommandIssuer(); - if(args == null || args.length == 0) { + if (args == null || args.length == 0) { //Process with no arguments - if(bukkitCommandIssuer.isPlayer()) { + if (bukkitCommandIssuer.isPlayer()) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); pluginRef.getChatManager().setOrToggleChatChannel(mmoPlayer, ChatChannel.PARTY); } else { @@ -45,7 +45,7 @@ public class PartyChatCommand extends BaseCommand { /* * Player Logic */ - if(bukkitCommandIssuer.getIssuer() instanceof Player) { + if (bukkitCommandIssuer.getIssuer() instanceof Player) { McMMOPlayer mmoPlayer = UserManager.getPlayer(bukkitCommandIssuer.getPlayer()); processCommandArgsPlayer(mmoPlayer, args); /* @@ -72,14 +72,14 @@ public class PartyChatCommand extends BaseCommand { * @param args command arguments */ private void processCommandArgsConsole(@NotNull String[] args) { - if(args.length <= 1) { + if (args.length <= 1) { //Only specific a party and not the message mcMMO.p.getLogger().severe("You need to specify a party name and then write a message afterwards."); } else { //Grab party Party targetParty = mcMMO.p.getPartyManager().getParty(args[0]); - if(targetParty != null) { + if (targetParty != null) { pluginRef.getChatManager().processConsoleMessage(StringUtils.buildStringAfterNthElement(args, 1), targetParty); } else { mcMMO.p.getLogger().severe("A party with that name doesn't exist!"); diff --git a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java index 571f1ae35..258242115 100644 --- a/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/database/ConvertDatabaseCommand.java @@ -28,7 +28,7 @@ public class ConvertDatabaseCommand implements CommandExecutor { } DatabaseManager oldDatabase = DatabaseManagerFactory.createDatabaseManager(previousType, mcMMO.getUsersFilePath(), mcMMO.p.getLogger(), mcMMO.p.getPurgeTime(), mcMMO.p.getAdvancedConfig().getStartingLevel()); - if(oldDatabase == null) { + if (oldDatabase == null) { sender.sendMessage("Unable to load the old database! Check your log for errors."); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java index ca54d293a..b9fb64d25 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddlevelsCommand.java @@ -35,7 +35,7 @@ public class AddlevelsCommand extends ExperienceCommand { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) { + if (mmoPlayer == null) { EventUtils.tryLevelChangeEvent(player, skill, value, xpRemoved, true, XPGainReason.COMMAND); } else { EventUtils.tryLevelChangeEvent(mmoPlayer, skill, value, xpRemoved, true, XPGainReason.COMMAND); @@ -45,7 +45,7 @@ public class AddlevelsCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.1", value)); @@ -53,7 +53,7 @@ public class AddlevelsCommand extends ExperienceCommand { @Override protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.1", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java index 25d77e5c0..953ad7436 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/AddxpCommand.java @@ -26,12 +26,11 @@ public class AddxpCommand extends ExperienceCommand { protected void handleCommand(Player player, PlayerProfile profile, PrimarySkillType skill, int value) { if (player != null) { //Check if player profile is loaded - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; UserManager.getPlayer(player).applyXpGain(skill, value, XPGainReason.COMMAND, XPGainSource.COMMAND); - } - else { + } else { profile.addXp(skill, value); profile.scheduleAsyncSave(); } @@ -39,7 +38,7 @@ public class AddxpCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardAll", value)); @@ -47,7 +46,7 @@ public class AddxpCommand extends ExperienceCommand { @Override protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.addxp.AwardSkill", value, mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java index 4bd6b4eeb..37e1d6c17 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/ExperienceCommand.java @@ -24,16 +24,16 @@ public abstract class ExperienceCommand implements TabExecutor { public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { PrimarySkillType skill; - if(args.length < 2) { + if (args.length < 2) { return false; } else { - if(args.length == 2 && !isSilent(args) || args.length == 3 && isSilent(args)) { + if (args.length == 2 && !isSilent(args) || args.length == 3 && isSilent(args)) { if (CommandUtils.noConsoleUsage(sender)) { return true; } if (!permissionsCheckSelf(sender)) { - if(command.getPermissionMessage() != null) + if (command.getPermissionMessage() != null) sender.sendMessage(command.getPermissionMessage()); sender.sendMessage("(mcMMO) No permission!"); return true; @@ -49,15 +49,13 @@ public abstract class ExperienceCommand implements TabExecutor { skill = null; } - if (skill != null && SkillTools.isChildSkill(skill)) - { + if (skill != null && SkillTools.isChildSkill(skill)) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); return true; } //Profile not loaded - if(UserManager.getPlayer(sender.getName()) == null) - { + if (UserManager.getPlayer(sender.getName()) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -65,7 +63,7 @@ public abstract class ExperienceCommand implements TabExecutor { editValues((Player) sender, UserManager.getPlayer(sender.getName()).getProfile(), skill, Integer.parseInt(args[1]), isSilent(args)); return true; - } else if((args.length == 3 && !isSilent(args)) + } else if ((args.length == 3 && !isSilent(args)) || (args.length == 4 && isSilent(args))) { if (!permissionsCheckOthers(sender)) { sender.sendMessage(command.getPermissionMessage()); @@ -82,8 +80,7 @@ public abstract class ExperienceCommand implements TabExecutor { skill = null; } - if (skill != null && SkillTools.isChildSkill(skill)) - { + if (skill != null && SkillTools.isChildSkill(skill)) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.ChildSkill")); return true; } @@ -104,14 +101,13 @@ public abstract class ExperienceCommand implements TabExecutor { //Check loading by name profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); - if(CommandUtils.unloadedProfile(sender, profile)) { + if (CommandUtils.unloadedProfile(sender, profile)) { return true; } } editValues(null, profile, skill, value, isSilent(args)); - } - else { + } else { editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill, value, isSilent(args)); } @@ -126,7 +122,7 @@ public abstract class ExperienceCommand implements TabExecutor { private boolean isSilent(String[] args) { int length = args.length; - if(length == 0) + if (length == 0) return false; return args[length-1].equalsIgnoreCase("-s"); @@ -159,8 +155,7 @@ public abstract class ExperienceCommand implements TabExecutor { protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { if (skill == null) { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); } } @@ -174,8 +169,7 @@ public abstract class ExperienceCommand implements TabExecutor { if (player != null) { handlePlayerMessageAll(player, value, isSilent); } - } - else { + } else { handleCommand(player, profile, skill, value); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java index 93089ac69..737d7f40a 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/MmoeditCommand.java @@ -41,7 +41,7 @@ public class MmoeditCommand extends ExperienceCommand { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { + if (mmoPlayer != null) { EventUtils.tryLevelEditEvent(mmoPlayer, skill, value, xpRemoved, value > skillLevel, XPGainReason.COMMAND, skillLevel); } else { EventUtils.tryLevelEditEvent(player, skill, value, xpRemoved, value > skillLevel, XPGainReason.COMMAND, skillLevel); @@ -51,7 +51,7 @@ public class MmoeditCommand extends ExperienceCommand { @Override protected void handlePlayerMessageAll(Player player, int value, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.mmoedit.AllSkills.1", value)); @@ -59,7 +59,7 @@ public class MmoeditCommand extends ExperienceCommand { @Override protected void handlePlayerMessageSkill(Player player, int value, PrimarySkillType skill, boolean isSilent) { - if(isSilent) + if (isSilent) return; player.sendMessage(LocaleLoader.getString("Commands.mmoedit.Modified.1", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), value)); diff --git a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java index edc99e2ad..e2fcd38ec 100644 --- a/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/experience/SkillresetCommand.java @@ -48,8 +48,7 @@ public class SkillresetCommand implements TabExecutor { if (args[0].equalsIgnoreCase("all")) { skill = null; - } - else { + } else { skill = mcMMO.p.getSkillTools().matchSkill(args[0]); } @@ -68,8 +67,7 @@ public class SkillresetCommand implements TabExecutor { if (args[1].equalsIgnoreCase("all")) { skill = null; - } - else { + } else { skill = mcMMO.p.getSkillTools().matchSkill(args[1]); } @@ -87,14 +85,13 @@ public class SkillresetCommand implements TabExecutor { profile = mcMMO.getDatabaseManager().loadPlayerProfile(playerName); //Check if it was present in DB - if(CommandUtils.unloadedProfile(sender, profile)) { + if (CommandUtils.unloadedProfile(sender, profile)) { return true; } } editValues(null, profile, skill); - } - else { + } else { editValues(mcMMOPlayer.getPlayer(), mcMMOPlayer.getProfile(), skill); } @@ -156,8 +153,7 @@ public class SkillresetCommand implements TabExecutor { protected static void handleSenderMessage(CommandSender sender, String playerName, PrimarySkillType skill) { if (skill == null) { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardAll.2", playerName)); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.addlevels.AwardSkill.2", mcMMO.p.getSkillTools().getLocalizedSkillName(skill), playerName)); } } @@ -171,8 +167,7 @@ public class SkillresetCommand implements TabExecutor { if (player != null) { handlePlayerMessageAll(player); } - } - else { + } else { handleCommand(player, profile, skill); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java index b8d835ef3..7ef2dc560 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyChangePasswordCommand.java @@ -12,8 +12,7 @@ import org.jetbrains.annotations.NotNull; public class PartyChangePasswordCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java index 52e99bd3c..06691c171 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCommand.java @@ -90,8 +90,7 @@ public class PartyCommand implements TabExecutor { } McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -207,8 +206,7 @@ public class PartyCommand implements TabExecutor { final McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Not Loaded - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return ImmutableList.of(); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java index 75a7c785c..b11ac69ff 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyCreateCommand.java @@ -19,8 +19,7 @@ public class PartyCreateCommand implements CommandExecutor { Player player = (Player) sender; McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java index 3e34078e8..892256cdb 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyInfoCommand.java @@ -23,8 +23,7 @@ public class PartyInfoCommand implements CommandExecutor { switch (args.length) { case 0: case 1: - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -70,8 +69,7 @@ public class PartyInfoCommand implements CommandExecutor { if (isUnlockedFeature(party, partyFeature)) { unlockedPartyFeatures.add(partyFeature.getLocaleString()); - } - else { + } else { lockedPartyFeatures.add(partyFeature.getFeatureLockedLocaleString()); } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java index 44822d82f..38a3e3a24 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyItemShareCommand.java @@ -20,8 +20,7 @@ import java.util.Locale; public class PartyItemShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -50,11 +49,9 @@ public class PartyItemShareCommand implements CommandExecutor { if (CommandUtils.shouldEnableToggle(args[2])) { toggle = true; - } - else if (CommandUtils.shouldDisableToggle(args[2])) { + } else if (CommandUtils.shouldDisableToggle(args[2])) { toggle = false; - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.Usage.2", "party", "itemshare", " ")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java index a5474d355..79b14b915 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyJoinCommand.java @@ -34,8 +34,7 @@ public class PartyJoinCommand implements CommandExecutor { Player player = (Player) sender; - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -62,8 +61,7 @@ public class PartyJoinCommand implements CommandExecutor { return true; } - if(mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) - { + if (mcMMO.p.getPartyManager().isPartyFull(player, targetParty)) { player.sendMessage(LocaleLoader.getString("Commands.Party.PartyFull", targetParty.toString())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java index eb87e0843..745fba90f 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyLockCommand.java @@ -18,8 +18,7 @@ public class PartyLockCommand implements CommandExecutor { case 1: if (args[0].equalsIgnoreCase("lock")) { togglePartyLock(sender, true); - } - else if (args[0].equalsIgnoreCase("unlock")) { + } else if (args[0].equalsIgnoreCase("unlock")) { togglePartyLock(sender, false); } @@ -33,11 +32,9 @@ public class PartyLockCommand implements CommandExecutor { if (CommandUtils.shouldEnableToggle(args[1])) { togglePartyLock(sender, true); - } - else if (CommandUtils.shouldDisableToggle(args[1])) { + } else if (CommandUtils.shouldDisableToggle(args[1])) { togglePartyLock(sender, false); - } - else { + } else { sendUsageStrings(sender); } @@ -55,8 +52,7 @@ public class PartyLockCommand implements CommandExecutor { } private void togglePartyLock(CommandSender sender, boolean lock) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java index f4ebdb510..c9c45453d 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartySubcommandType.java @@ -30,20 +30,15 @@ public enum PartySubcommandType { if (commandName.equalsIgnoreCase("?")) { return HELP; - } - else if (commandName.equalsIgnoreCase("q") || commandName.equalsIgnoreCase("leave")) { + } else if (commandName.equalsIgnoreCase("q") || commandName.equalsIgnoreCase("leave")) { return QUIT; - } - else if (commandName.equalsIgnoreCase("leader")) { + } else if (commandName.equalsIgnoreCase("leader")) { return OWNER; - } - else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) { + } else if (commandName.equalsIgnoreCase("xpshare") || commandName.equalsIgnoreCase("shareexp") || commandName.equalsIgnoreCase("sharexp")) { return XPSHARE; - } - else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) { + } else if (commandName.equalsIgnoreCase("shareitem") || commandName.equalsIgnoreCase("shareitems")) { return ITEMSHARE; - } - else if (commandName.equalsIgnoreCase("ally")) { + } else if (commandName.equalsIgnoreCase("ally")) { return ALLIANCE; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java index 8322beecf..098cdc3a2 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/PartyXpShareCommand.java @@ -17,8 +17,7 @@ import org.jetbrains.annotations.NotNull; public class PartyXpShareCommand implements CommandExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, String[] args) { - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java index e39e7c3e2..231f85456 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/alliance/PartyAllianceCommand.java @@ -37,8 +37,7 @@ public class PartyAllianceCommand implements TabExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java index 9822860f6..3b589ad0b 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptAnyCommand.java @@ -21,8 +21,7 @@ public class PtpAcceptAnyCommand implements CommandExecutor { if (ptpRecord.isConfirmRequired()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Disabled")); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.ptp.AcceptAny.Enabled")); } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java index 19c98ad6a..c5c22aad3 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpAcceptCommand.java @@ -21,8 +21,7 @@ public class PtpAcceptCommand implements CommandExecutor { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -56,8 +55,7 @@ public class PtpAcceptCommand implements CommandExecutor { if (!Permissions.partyTeleportWorld(target, targetWorld)) { target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return true; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(target, playerWorld)) { target.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", playerWorld.getName())); return true; } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java index 10f0f1d98..fee032c17 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpCommand.java @@ -45,22 +45,20 @@ public class PtpCommand implements TabExecutor { Player player = (Player) sender; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return true; } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(player.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(player.getWorld())) return true; if (!UserManager.hasPlayerDataKey(player)) { return true; } - if(UserManager.getPlayer((Player) sender) == null) - { + if (UserManager.getPlayer((Player) sender) == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -171,8 +169,7 @@ public class PtpCommand implements TabExecutor { if (!Permissions.partyTeleportWorld(target, targetWorld)) { player.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(player, targetWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(player, targetWorld)) { player.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; } @@ -228,14 +225,12 @@ public class PtpCommand implements TabExecutor { } protected static void handleTeleportWarmup(Player teleportingPlayer, Player targetPlayer) { - if(UserManager.getPlayer(targetPlayer) == null) - { + if (UserManager.getPlayer(targetPlayer) == null) { targetPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } - if(UserManager.getPlayer(teleportingPlayer) == null) - { + if (UserManager.getPlayer(teleportingPlayer) == null) { teleportingPlayer.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } @@ -250,8 +245,7 @@ public class PtpCommand implements TabExecutor { if (warmup > 0) { teleportingPlayer.sendMessage(LocaleLoader.getString("Teleport.Commencing", warmup)); mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(teleportingPlayer, new TeleportationWarmup(mcMMOPlayer, mcMMOTarget), 20 * warmup); - } - else { + } else { EventUtils.handlePartyTeleportEvent(teleportingPlayer, targetPlayer); } } diff --git a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java index aad4df9b9..e3ef50491 100644 --- a/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/party/teleport/PtpToggleCommand.java @@ -21,8 +21,7 @@ public class PtpToggleCommand implements CommandExecutor { if (ptpRecord.isEnabled()) { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Disabled")); - } - else { + } else { sender.sendMessage(LocaleLoader.getString("Commands.ptp.Enabled")); } diff --git a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java index dcfcdcdbe..48586ef59 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/McrankCommand.java @@ -3,7 +3,7 @@ package com.gmail.nossr50.commands.player; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.runnables.commands.McrankCommandAsyncTask; +import com.gmail.nossr50.runnables.commands.McRankCommandAsyncTask; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; @@ -85,8 +85,7 @@ public class McrankCommand implements TabExecutor { if (sender instanceof Player) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName()); - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return; } @@ -111,7 +110,7 @@ public class McrankCommand implements TabExecutor { boolean useBoard = mcMMO.p.getGeneralConfig().getScoreboardsEnabled() && (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getRankUseBoard()); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getRankUseChat(); - mcMMO.p.getFoliaLib().getImpl().runAsync(new McrankCommandAsyncTask(playerName, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getImpl().runAsync(new McRankCommandAsyncTask(playerName, sender, useBoard, useChat)); } private long getCDSeconds(McMMOPlayer mcMMOPlayer, long cooldownMillis) { diff --git a/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java b/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java index 86b1757e9..12e966a6c 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/MctopCommand.java @@ -4,7 +4,7 @@ import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.runnables.commands.MctopCommandAsyncTask; +import com.gmail.nossr50.runnables.commands.McTopCommandAsyncTask; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.commands.CommandUtils; @@ -115,7 +115,7 @@ public class MctopCommand implements TabExecutor { boolean useBoard = (sender instanceof Player) && (mcMMO.p.getGeneralConfig().getTopUseBoard()); boolean useChat = !useBoard || mcMMO.p.getGeneralConfig().getTopUseChat(); - mcMMO.p.getFoliaLib().getImpl().runAsync(new MctopCommandAsyncTask(page, skill, sender, useBoard, useChat)); + mcMMO.p.getFoliaLib().getImpl().runAsync(new McTopCommandAsyncTask(page, skill, sender, useBoard, useChat)); } private PrimarySkillType extractSkill(CommandSender sender, String skillName) { diff --git a/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java b/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java index e780fa19d..7fa7d04ff 100644 --- a/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/player/XPBarCommand.java @@ -24,22 +24,22 @@ public class XPBarCommand implements TabExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { - if(sender instanceof Player) { + if (sender instanceof Player) { McMMOPlayer mmoPlayer = UserManager.getPlayer((Player) sender); - if(mmoPlayer == null) { + if (mmoPlayer == null) { NotificationManager.sendPlayerInformationChatOnlyPrefixed(mmoPlayer.getPlayer(), "Profile.PendingLoad"); return false; } - if(args.length == 0) { + if (args.length == 0) { return false; - } else if(args.length < 2) { + } else if (args.length < 2) { String option = args[0]; - if(option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { + if (option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) { mmoPlayer.getExperienceBarManager().xpBarSettingToggle(ExperienceBarManager.XPBarSettingTarget.RESET, null); return true; - } else if(option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.DISABLE.toString())) { + } else if (option.equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.DISABLE.toString())) { mmoPlayer.getExperienceBarManager().disableAllBars(); return true; } else { @@ -50,7 +50,7 @@ public class XPBarCommand implements TabExecutor { } else if (args.length == 2) { String skillName = args[1]; - if(SkillUtils.isSkill(skillName)) { + if (SkillUtils.isSkill(skillName)) { PrimarySkillType targetSkill = mcMMO.p.getSkillTools().matchSkill(skillName); @@ -58,7 +58,7 @@ public class XPBarCommand implements TabExecutor { String option = args[0].toLowerCase(); ExperienceBarManager.XPBarSettingTarget settingTarget = getSettingTarget(option); - if(settingTarget != null && settingTarget != ExperienceBarManager.XPBarSettingTarget.RESET) { + if (settingTarget != null && settingTarget != ExperienceBarManager.XPBarSettingTarget.RESET) { //Change setting mmoPlayer.getExperienceBarManager().xpBarSettingToggle(settingTarget, targetSkill); return true; @@ -103,7 +103,7 @@ public class XPBarCommand implements TabExecutor { return StringUtil.copyPartialMatches(args[0], options, new ArrayList<>(ExperienceBarManager.XPBarSettingTarget.values().length)); case 2: - if(!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) + if (!args[0].equalsIgnoreCase(ExperienceBarManager.XPBarSettingTarget.RESET.toString())) return StringUtil.copyPartialMatches(args[1], mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES, new ArrayList<>(mcMMO.p.getSkillTools().LOCALIZED_SKILL_NAMES.size())); default: return ImmutableList.of(); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java index 64950211c..d04d3d4d4 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AcrobaticsCommand.java @@ -29,7 +29,7 @@ public class AcrobaticsCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ACROBATICS_DODGE if (canDodge) { - String[] dodgeStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ACROBATICS_DODGE); + final String[] dodgeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_DODGE); dodgeChance = dodgeStrings[0]; dodgeChanceLucky = dodgeStrings[1]; } @@ -54,9 +54,8 @@ public class AcrobaticsCommand extends SkillCommand { AbstractSubSkill abstractSubSkill = InteractionManager.getAbstractByName("Roll"); - if(abstractSubSkill != null) - { - String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ACROBATICS_ROLL); + if (abstractSubSkill != null) { + String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); messages.add(getStatMessage(SubSkillType.ACROBATICS_ROLL, rollStrings[0]) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", rollStrings[1]) : "")); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java index be34ebe2f..9fa9281a7 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AlchemyCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.alchemy.AlchemyManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import net.kyori.adventure.text.Component; @@ -30,14 +29,7 @@ public class AlchemyCommand extends SkillCommand { } protected String[] calculateAbilityDisplayValues(Player player) { - //TODO: Needed? - if(UserManager.getPlayer(player) == null) - { - player.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); - return new String[] {"DATA NOT LOADED", "DATA NOT LOADED"}; - } - - AlchemyManager alchemyManager = UserManager.getPlayer(player).getAlchemyManager(); + AlchemyManager alchemyManager = mmoPlayer.getAlchemyManager(); String[] displayValues = new String[2]; boolean isLucky = Permissions.lucky(player, PrimarySkillType.ALCHEMY); @@ -59,7 +51,7 @@ public class AlchemyCommand extends SkillCommand { // ALCHEMY_CONCOCTIONS if (canConcoctions) { - AlchemyManager alchemyManager = UserManager.getPlayer(player).getAlchemyManager(); + AlchemyManager alchemyManager = mmoPlayer.getAlchemyManager(); tier = alchemyManager.getTier(); ingredientCount = alchemyManager.getIngredients().size(); ingredientList = alchemyManager.getIngredientList(); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java index dd7bf8d4b..d916f458a 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ArcheryCommand.java @@ -33,14 +33,14 @@ public class ArcheryCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ARCHERY_ARROW_RETRIEVAL if (canRetrieve) { - String[] retrieveStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ARCHERY_ARROW_RETRIEVAL); + String[] retrieveStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ARCHERY_ARROW_RETRIEVAL); retrieveChance = retrieveStrings[0]; retrieveChanceLucky = retrieveStrings[1]; } // ARCHERY_DAZE if (canDaze) { - String[] dazeStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ARCHERY_DAZE); + String[] dazeStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ARCHERY_DAZE); dazeChance = dazeStrings[0]; dazeChanceLucky = dazeStrings[1]; } @@ -76,7 +76,7 @@ public class ArcheryCommand extends SkillCommand { messages.add(getStatMessage(SubSkillType.ARCHERY_SKILL_SHOT, skillShotBonus)); } - if(Permissions.canUseSubSkill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java index bcfb38ed0..ce1907c39 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/AxesCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.axes.Axes; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -38,7 +37,7 @@ public class AxesCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // ARMOR IMPACT if (canImpact) { - impactDamage = UserManager.getPlayer(player).getAxesManager().getImpactDurabilityDamage(); + impactDamage = mmoPlayer.getAxesManager().getImpactDurabilityDamage(); } // AXE MASTERY @@ -48,7 +47,7 @@ public class AxesCommand extends SkillCommand { // CRITICAL HIT if (canCritical) { - String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.AXES_CRITICAL_STRIKES); + String[] criticalHitStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.AXES_CRITICAL_STRIKES); critChance = criticalHitStrings[0]; critChanceLucky = criticalHitStrings[1]; } @@ -96,7 +95,7 @@ public class AxesCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", skullSplitterLengthEndurance) : "")); } - if(Permissions.canUseSubSkill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, SubSkillType.AXES_AXES_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.AXES_AXES_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.AXES_AXES_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java index bbf29caaf..e5f78ac91 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/CrossbowsCommand.java @@ -1,9 +1,7 @@ package com.gmail.nossr50.commands.skills; -import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -42,7 +40,6 @@ public class CrossbowsCommand extends SkillCommand { protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); if (mmoPlayer == null) { return messages; } @@ -57,7 +54,7 @@ public class CrossbowsCommand extends SkillCommand { String.valueOf(mmoPlayer.getCrossbowsManager().getTrickShotMaxBounceCount()))); } - if(Permissions.canUseSubSkill(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { messages.add(getStatMessage(CROSSBOWS_CROSSBOWS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, CROSSBOWS_CROSSBOWS_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java index 952766b15..829e4644f 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/ExcavationCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import net.kyori.adventure.text.Component; @@ -45,7 +44,7 @@ public class ExcavationCommand extends SkillCommand { protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - ExcavationManager excavationManager = UserManager.getPlayer(player).getExcavationManager(); + ExcavationManager excavationManager = mmoPlayer.getExcavationManager(); if (canGigaDrill) { messages.add(getStatMessage(SubSkillType.EXCAVATION_GIGA_DRILL_BREAKER, gigaDrillBreakerLength) @@ -54,7 +53,7 @@ public class ExcavationCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Excavation.Effect.Length", gigaDrillBreakerLength) + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", gigaDrillBreakerLengthEndurance) : "")); } - if(Permissions.canUseSubSkill(player, SubSkillType.EXCAVATION_ARCHAEOLOGY)) { + if (Permissions.canUseSubSkill(player, SubSkillType.EXCAVATION_ARCHAEOLOGY)) { messages.add(getStatMessage(false, false, SubSkillType.EXCAVATION_ARCHAEOLOGY, percent.format(excavationManager.getArchaelogyExperienceOrbChance() / 100.0D))); messages.add(getStatMessage(true, false, SubSkillType.EXCAVATION_ARCHAEOLOGY, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java index 6b188d2d7..c955fdf18 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/FishingCommand.java @@ -8,7 +8,6 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.fishing.FishingManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; @@ -50,7 +49,7 @@ public class FishingCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { - FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); + FishingManager fishingManager = mmoPlayer.getFishingManager(); // TREASURE HUNTER if (canTreasureHunt) { @@ -73,7 +72,7 @@ public class FishingCommand extends SkillCommand { } } - if(totalEnchantChance >= 1) + if (totalEnchantChance >= 1) magicChance = percent.format(totalEnchantChance / 100.0); else magicChance = percent.format(0); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java index 8a5ce8d33..5c9028897 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/HerbalismCommand.java @@ -49,13 +49,13 @@ public class HerbalismCommand extends SkillCommand { // DOUBLE DROPS if (canDoubleDrop) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_DOUBLE_DROPS); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } if (canTripleDrop) { - String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_VERDANT_BOUNTY); + String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_VERDANT_BOUNTY); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; } @@ -76,21 +76,21 @@ public class HerbalismCommand extends SkillCommand { if (canGreenThumbBlocks || canGreenThumbPlants) { greenThumbStage = RankUtils.getRank(player, SubSkillType.HERBALISM_GREEN_THUMB); - String[] greenThumbStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_GREEN_THUMB); + String[] greenThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_GREEN_THUMB); greenThumbChance = greenThumbStrings[0]; greenThumbChanceLucky = greenThumbStrings[1]; } // HYLIAN LUCK if (hasHylianLuck) { - String[] hylianLuckStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_HYLIAN_LUCK); + String[] hylianLuckStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_HYLIAN_LUCK); hylianLuckChance = hylianLuckStrings[0]; hylianLuckChanceLucky = hylianLuckStrings[1]; } // SHROOM THUMB if (canShroomThumb) { - String[] shroomThumbStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.HERBALISM_SHROOM_THUMB); + String[] shroomThumbStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.HERBALISM_SHROOM_THUMB); shroomThumbChance = shroomThumbStrings[0]; shroomThumbChanceLucky = shroomThumbStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java new file mode 100644 index 000000000..176a9e9a4 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/commands/skills/MacesCommand.java @@ -0,0 +1,52 @@ +//package com.gmail.nossr50.commands.skills; +// +//import com.gmail.nossr50.datatypes.player.McMMOPlayer; +//import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +//import com.gmail.nossr50.util.player.UserManager; +//import com.gmail.nossr50.util.skills.CombatUtils; +//import com.gmail.nossr50.util.skills.SkillUtils; +//import com.gmail.nossr50.util.text.TextComponentFactory; +//import net.kyori.adventure.text.Component; +//import org.bukkit.ChatColor; +//import org.bukkit.entity.Player; +// +//import java.util.ArrayList; +//import java.util.List; +// +//import static com.gmail.nossr50.datatypes.skills.SubSkillType.MACES_MACES_LIMIT_BREAK; +// +//public class MacesCommand extends SkillCommand { +// +// public MacesCommand() { +// super(PrimarySkillType.MACES); +// } +// +// @Override +// protected void dataCalculations(Player player, float skillValue) {} +// +// @Override +// protected void permissionsCheck(Player player) {} +// +// @Override +// protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { +// List messages = new ArrayList<>(); +// +// if (SkillUtils.canUseSubskill(player, MACES_MACES_LIMIT_BREAK)) { +// messages.add(getStatMessage(MACES_MACES_LIMIT_BREAK, +// String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, MACES_MACES_LIMIT_BREAK, 1000)))); +// } +// +// messages.add(ChatColor.GRAY + "The Maces skill is a work in progress and is still being developed," + +// " feedback would be appreciated in the mcMMO discord server."); +// return messages; +// } +// +// @Override +// protected List getTextComponents(Player player) { +// List textComponents = new ArrayList<>(); +// +// TextComponentFactory.getSubSkillTextComponents(player, textComponents, PrimarySkillType.MACES); +// +// return textComponents; +// } +//} diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java index b756dd282..9247cee3c 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MiningCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -45,7 +44,7 @@ public class MiningCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // BLAST MINING if (canBlast || canDemoExpert || canBiggerBombs) { - MiningManager miningManager = UserManager.getPlayer(player).getMiningManager(); + MiningManager miningManager = mmoPlayer.getMiningManager(); blastMiningRank = miningManager.getBlastMiningTier(); bonusTNTDrops = miningManager.getDropMultiplier(); @@ -57,14 +56,14 @@ public class MiningCommand extends SkillCommand { // Mastery TRIPLE DROPS if (canTripleDrop) { - String[] masteryTripleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.MINING_MOTHER_LODE); + String[] masteryTripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.MINING_MOTHER_LODE); tripleDropChance = masteryTripleDropStrings[0]; tripleDropChanceLucky = masteryTripleDropStrings[1]; } // DOUBLE DROPS if (canDoubleDrop) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.MINING_DOUBLE_DROPS); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.MINING_DOUBLE_DROPS); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } @@ -112,7 +111,7 @@ public class MiningCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Mining.Effect.DropChance", doubleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } - if(canTripleDrop) { + if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.MINING_MOTHER_LODE, tripleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java index 3a085a5cf..795f4005c 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/MmoInfoCommand.java @@ -26,15 +26,12 @@ public class MmoInfoCommand implements TabExecutor { /* * Only allow players to use this command */ - if(commandSender instanceof Player player) - { - if(args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) + if (commandSender instanceof Player player) { + if (args == null || args.length < 1 || args[0] == null || args[0].isEmpty()) return false; - if(Permissions.mmoinfo(player)) - { - if(args[0].equalsIgnoreCase( "???")) - { + if (Permissions.mmoinfo(player)) { + if (args[0].equalsIgnoreCase( "???")) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", "???")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); @@ -57,9 +54,8 @@ public class MmoInfoCommand implements TabExecutor { } public SubSkillType matchSubSkill(String name) { - for(SubSkillType subSkillType : SubSkillType.values()) - { - if(subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(name) + for(SubSkillType subSkillType : SubSkillType.values()) { + if (subSkillType.getNiceNameNoSpaces(subSkillType).equalsIgnoreCase(name) || subSkillType.name().equalsIgnoreCase(name)) return subSkillType; } @@ -74,8 +70,7 @@ public class MmoInfoCommand implements TabExecutor { return ImmutableList.of(); } - private void displayInfo(Player player, SubSkillType subSkillType) - { + private void displayInfo(Player player, SubSkillType subSkillType) { player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", subSkillType.getLocaleName())); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); diff --git a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java index 32927ddcf..af23a880d 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/RepairCommand.java @@ -10,7 +10,6 @@ import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.repair.RepairManager; import com.gmail.nossr50.skills.repair.repairables.Repairable; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -68,7 +67,7 @@ public class RepairCommand extends SkillCommand { // SUPER REPAIR if (canSuperRepair) { - String[] superRepairStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.REPAIR_SUPER_REPAIR); + String[] superRepairStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.REPAIR_SUPER_REPAIR); superRepairChance = superRepairStrings[0]; superRepairChanceLucky = superRepairStrings[1]; } @@ -94,7 +93,7 @@ public class RepairCommand extends SkillCommand { List messages = new ArrayList<>(); if (canArcaneForge) { - RepairManager repairManager = UserManager.getPlayer(player).getRepairManager(); + RepairManager repairManager = mmoPlayer.getRepairManager(); messages.add(getStatMessage(false, true, SubSkillType.REPAIR_ARCANE_FORGING, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java index 93a748023..80b12108e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SalvageCommand.java @@ -6,7 +6,6 @@ import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.skills.salvage.Salvage; import com.gmail.nossr50.skills.salvage.SalvageManager; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; import net.kyori.adventure.text.Component; @@ -38,7 +37,7 @@ public class SalvageCommand extends SkillCommand { @Override protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - SalvageManager salvageManager = UserManager.getPlayer(player).getSalvageManager(); + SalvageManager salvageManager = mmoPlayer.getSalvageManager(); if (canScrapCollector) { messages.add(getStatMessage(false, true, diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java index e8ab95e02..4e20a761b 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillCommand.java @@ -34,6 +34,7 @@ public abstract class SkillCommand implements TabExecutor { protected DecimalFormat percent = new DecimalFormat("##0.00%"); protected DecimalFormat decimal = new DecimalFormat("##0.00"); + protected McMMOPlayer mmoPlayer; private final CommandExecutor skillGuideCommand; @@ -53,9 +54,9 @@ public abstract class SkillCommand implements TabExecutor { } Player player = (Player) sender; - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + mmoPlayer = UserManager.getPlayer(player); - if (mcMMOPlayer == null) { + if (mmoPlayer == null) { sender.sendMessage(LocaleLoader.getString("Profile.PendingLoad")); return true; } @@ -63,7 +64,7 @@ public abstract class SkillCommand implements TabExecutor { if (args.length == 0) { boolean isLucky = Permissions.lucky(player, skill); boolean hasEndurance = PerksUtils.handleActivationPerks(player, 0, 0) != 0; - float skillValue = mcMMOPlayer.getSkillLevel(skill); + float skillValue = mmoPlayer.getSkillLevel(skill); //Send the players a few blank lines to make finding the top of the skill command easier if (mcMMO.p.getAdvancedConfig().doesSkillCommandSendBlankLines()) @@ -75,7 +76,7 @@ public abstract class SkillCommand implements TabExecutor { dataCalculations(player, skillValue); sendSkillCommandHeader(mcMMO.p.getSkillTools().getLocalizedSkillName(skill), - player, mcMMOPlayer, (int) skillValue); + player, mmoPlayer, (int) skillValue); //Make JSON text components List subskillTextComponents = getTextComponents(player); @@ -87,8 +88,7 @@ public abstract class SkillCommand implements TabExecutor { TextComponentFactory.sendPlayerSubSkillList(player, subskillTextComponents); - /*for(TextComponent tc : subskillTextComponents) - { + /*for(TextComponent tc : subskillTextComponents) { player.spigot().sendMessage(new TextComponent[]{tc, new TextComponent(": TESTING")}); }*/ @@ -148,8 +148,7 @@ public abstract class SkillCommand implements TabExecutor { // send header player.sendMessage(LocaleLoader.getString("Skills.Overhaul.Header", skillName)); - if(!SkillTools.isChildSkill(skill)) - { + if (!SkillTools.isChildSkill(skill)) { /* * NON-CHILD SKILLS */ @@ -174,10 +173,8 @@ public abstract class SkillCommand implements TabExecutor { StringBuilder parentMessage = new StringBuilder(); - for(int i = 0; i < parentList.size(); i++) - { - if(i+1 < parentList.size()) - { + for(int i = 0; i < parentList.size(); i++) { + if (i+1 < parentList.size()) { parentMessage.append(LocaleLoader.getString("Effects.Child.ParentList", mcMMO.p.getSkillTools().getLocalizedSkillName(parentList.get(i)), mcMMOPlayer.getSkillLevel(parentList.get(i)))); parentMessage.append(ChatColor.GRAY).append(", "); } else { @@ -236,11 +233,9 @@ public abstract class SkillCommand implements TabExecutor { int length; - if(abilityLengthCap <= 0) - { + if (abilityLengthCap <= 0) { length = 2 + (int) (skillValue / abilityLengthVar); - } - else { + } else { length = 2 + (int) (Math.min(abilityLengthCap, skillValue) / abilityLengthVar); } @@ -253,27 +248,24 @@ public abstract class SkillCommand implements TabExecutor { return new String[] { String.valueOf(length), String.valueOf(enduranceLength) }; } - protected String getStatMessage(SubSkillType subSkillType, String... vars) - { + protected String getStatMessage(SubSkillType subSkillType, String... vars) { return getStatMessage(false, false, subSkillType, vars); } - protected String getStatMessage(boolean isExtra, boolean isCustom, SubSkillType subSkillType, String... vars) - { + protected String getStatMessage(boolean isExtra, boolean isCustom, SubSkillType subSkillType, String... vars) { String templateKey = isCustom ? "Ability.Generic.Template.Custom" : "Ability.Generic.Template"; String statDescriptionKey = !isExtra ? subSkillType.getLocaleKeyStatDescription() : subSkillType.getLocaleKeyStatExtraDescription(); - if(isCustom) + if (isCustom) return LocaleLoader.getString(templateKey, LocaleLoader.getString(statDescriptionKey, vars)); - else - { + else { String[] mergedList = NotificationManager.addItemToFirstPositionOfArray(LocaleLoader.getString(statDescriptionKey), vars); return LocaleLoader.getString(templateKey, mergedList); } } protected String getLimitBreakDescriptionParameter() { - if(mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { + if (mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { return "(PVP/PVE)"; } else { return "(PVP)"; diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java index ed471f188..6b9342598 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SkillGuideCommand.java @@ -77,8 +77,7 @@ public class SkillGuideCommand implements CommandExecutor { while (allStrings.size() < 9) { if (pageIndexStart + allStrings.size() > guide.size()) { allStrings.add(""); - } - else { + } else { allStrings.add(guide.get(pageIndexStart + (allStrings.size() - 1))); } } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java index 297662e10..0ca68a964 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SmeltingCommand.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -34,7 +33,7 @@ public class SmeltingCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // FUEL EFFICIENCY if (canFuelEfficiency) { - burnTimeModifier = String.valueOf(UserManager.getPlayer(player).getSmeltingManager().getFuelEfficiencyMultiplier()); + burnTimeModifier = String.valueOf(mmoPlayer.getSmeltingManager().getFuelEfficiencyMultiplier()); } // FLUX MINING @@ -46,7 +45,7 @@ public class SmeltingCommand extends SkillCommand { // SECOND SMELT if (canSecondSmelt) { - String[] secondSmeltStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.SMELTING_SECOND_SMELT); + String[] secondSmeltStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.SMELTING_SECOND_SMELT); str_secondSmeltChance = secondSmeltStrings[0]; str_secondSmeltChanceLucky = secondSmeltStrings[1]; } @@ -81,7 +80,7 @@ public class SmeltingCommand extends SkillCommand { if (canUnderstandTheArt) { messages.add(getStatMessage(false, true, SubSkillType.SMELTING_UNDERSTANDING_THE_ART, - String.valueOf(UserManager.getPlayer(player).getSmeltingManager().getVanillaXpMultiplier()))); + String.valueOf(mmoPlayer.getSmeltingManager().getVanillaXpMultiplier()))); } return messages; diff --git a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java index 03d15d4ce..c44af71ef 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/SwordsCommand.java @@ -5,7 +5,6 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -39,7 +38,7 @@ public class SwordsCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // SWORDS_COUNTER_ATTACK if (canCounter) { - String[] counterStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.SWORDS_COUNTER_ATTACK); + String[] counterStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.SWORDS_COUNTER_ATTACK); counterChance = counterStrings[0]; counterChanceLucky = counterStrings[1]; } @@ -102,13 +101,12 @@ public class SwordsCommand extends SkillCommand { + (hasEndurance ? LocaleLoader.getString("Perks.ActivationTime.Bonus", serratedStrikesLengthEndurance) : "")); } - if(SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) - { + if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_STAB)) { messages.add(getStatMessage(SubSkillType.SWORDS_STAB, - String.valueOf(UserManager.getPlayer(player).getSwordsManager().getStabDamage()))); + String.valueOf(mmoPlayer.getSwordsManager().getStabDamage()))); } - if(SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { + if (SkillUtils.canUseSubskill(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java index fc6fd2e46..12430fc02 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TamingCommand.java @@ -35,7 +35,7 @@ public class TamingCommand extends SkillCommand { @Override protected void dataCalculations(Player player, float skillValue) { if (canGore) { - String[] goreStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.TAMING_GORE); + String[] goreStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.TAMING_GORE); goreChance = goreStrings[0]; goreChanceLucky = goreStrings[1]; } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java index ff4165659..21d37eb7e 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/TridentsCommand.java @@ -1,8 +1,6 @@ package com.gmail.nossr50.commands.skills; -import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.SkillUtils; import com.gmail.nossr50.util.text.TextComponentFactory; @@ -32,17 +30,13 @@ public class TridentsCommand extends SkillCommand { @Override protected List statsDisplay(Player player, float skillValue, boolean hasEndurance, boolean isLucky) { List messages = new ArrayList<>(); - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) { - return messages; - } - if(SkillUtils.canUseSubskill(player, TRIDENTS_TRIDENTS_LIMIT_BREAK)) { + if (SkillUtils.canUseSubskill(player, TRIDENTS_TRIDENTS_LIMIT_BREAK)) { messages.add(getStatMessage(TRIDENTS_TRIDENTS_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, TRIDENTS_TRIDENTS_LIMIT_BREAK, 1000)))); } - if(SkillUtils.canUseSubskill(player, TRIDENTS_IMPALE)) { + if (SkillUtils.canUseSubskill(player, TRIDENTS_IMPALE)) { messages.add(getStatMessage(TRIDENTS_IMPALE, String.valueOf(mmoPlayer.getTridentsManager().impaleDamageBonus()))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java index 554eca6b3..6a85468c8 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/UnarmedCommand.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.util.Permissions; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.CombatUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -40,7 +39,7 @@ public class UnarmedCommand extends SkillCommand { protected void dataCalculations(Player player, float skillValue) { // UNARMED_ARROW_DEFLECT if (canDeflect) { - String[] deflectStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.UNARMED_ARROW_DEFLECT); + String[] deflectStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_ARROW_DEFLECT); deflectChance = deflectStrings[0]; deflectChanceLucky = deflectStrings[1]; } @@ -54,19 +53,19 @@ public class UnarmedCommand extends SkillCommand { // UNARMED_DISARM if (canDisarm) { - String[] disarmStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.UNARMED_DISARM); + String[] disarmStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_DISARM); disarmChance = disarmStrings[0]; disarmChanceLucky = disarmStrings[1]; } // IRON ARM if (canIronArm) { - ironArmBonus = UserManager.getPlayer(player).getUnarmedManager().getSteelArmStyleDamage(); + ironArmBonus = mmoPlayer.getUnarmedManager().getSteelArmStyleDamage(); } // IRON GRIP if (canIronGrip) { - String[] ironGripStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.UNARMED_IRON_GRIP); + String[] ironGripStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.UNARMED_IRON_GRIP); ironGripChance = ironGripStrings[0]; ironGripChanceLucky = ironGripStrings[1]; } @@ -114,7 +113,7 @@ public class UnarmedCommand extends SkillCommand { //messages.add(LocaleLoader.getString("Unarmed.Ability.Chance.IronGrip", ironGripChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", ironGripChanceLucky) : "")); } - if(Permissions.canUseSubSkill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { + if (Permissions.canUseSubSkill(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { messages.add(getStatMessage(SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, String.valueOf(CombatUtils.getLimitBreakDamageAgainstQuality(player, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK, 1000)))); } diff --git a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java index 1dd4beeb0..33dd0f071 100644 --- a/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java +++ b/src/main/java/com/gmail/nossr50/commands/skills/WoodcuttingCommand.java @@ -40,8 +40,8 @@ public class WoodcuttingCommand extends SkillCommand { } //Clean Cuts - if(canTripleDrop) { - String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.WOODCUTTING_CLEAN_CUTS); + if (canTripleDrop) { + String[] tripleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_CLEAN_CUTS); tripleDropChance = tripleDropStrings[0]; tripleDropChanceLucky = tripleDropStrings[1]; } @@ -55,7 +55,7 @@ public class WoodcuttingCommand extends SkillCommand { } private void setDoubleDropClassicChanceStrings(Player player) { - String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.WOODCUTTING_HARVEST_LUMBER); + String[] doubleDropStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.WOODCUTTING_HARVEST_LUMBER); doubleDropChance = doubleDropStrings[0]; doubleDropChanceLucky = doubleDropStrings[1]; } @@ -80,7 +80,7 @@ public class WoodcuttingCommand extends SkillCommand { + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", doubleDropChanceLucky) : "")); } - if(canTripleDrop) { + if (canTripleDrop) { messages.add(getStatMessage(SubSkillType.WOODCUTTING_CLEAN_CUTS, tripleDropChance) + (isLucky ? LocaleLoader.getString("Perks.Lucky.Bonus", tripleDropChanceLucky) : "")); } @@ -89,7 +89,7 @@ public class WoodcuttingCommand extends SkillCommand { if (canKnockOnWood) { String lootNote; - if(RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { lootNote = LocaleLoader.getString("Woodcutting.SubSkill.KnockOnWood.Loot.Rank2"); } else { lootNote = LocaleLoader.getString("Woodcutting.SubSkill.KnockOnWood.Loot.Normal"); diff --git a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java index da882f098..15b7d74c8 100644 --- a/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java +++ b/src/main/java/com/gmail/nossr50/config/AdvancedConfig.java @@ -504,8 +504,7 @@ public class AdvancedConfig extends BukkitConfig { */ - /*public ChatColor getJSONStatHoverElementColor(StatType statType, boolean isPrefix) - { + /*public ChatColor getJSONStatHoverElementColor(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Color"; @@ -517,50 +516,41 @@ public class AdvancedConfig extends BukkitConfig { * * @return the ChatColor for this element */ - /*public ChatColor getJSONStatHoverDetailsColor() - { + /*public ChatColor getJSONStatHoverDetailsColor() { String keyLocation = "Style.JSON.Hover.Details.Header.Color"; return getChatColorFromKey(keyLocation); } - public boolean isJSONDetailsHeaderBold() - { + public boolean isJSONDetailsHeaderBold() { return config.getBoolean("Style.JSON.Hover.Details.Header.Bold"); } - public boolean isJSONDetailsHeaderItalic() - { + public boolean isJSONDetailsHeaderItalic() { return config.getBoolean("Style.JSON.Hover.Details.Header.Italics"); } - public boolean isJSONDetailsHeaderUnderlined() - { + public boolean isJSONDetailsHeaderUnderlined() { return config.getBoolean("Style.JSON.Hover.Details.Header.Underlined"); } - public ChatColor getJSONStatHoverDescriptionColor() - { + public ChatColor getJSONStatHoverDescriptionColor() { String keyLocation = "Style.JSON.Hover.Details.Description.Color"; return getChatColorFromKey(keyLocation); } - public boolean isJSONDetailsDescriptionBold() - { + public boolean isJSONDetailsDescriptionBold() { return config.getBoolean("Style.JSON.Hover.Details.Description.Bold"); } - public boolean isJSONDetailsDescriptionItalic() - { + public boolean isJSONDetailsDescriptionItalic() { return config.getBoolean("Style.JSON.Hover.Details.Description.Italics"); } - public boolean isJSONDetailsDescriptionUnderlined() - { + public boolean isJSONDetailsDescriptionUnderlined() { return config.getBoolean("Style.JSON.Hover.Details.Description.Underlined"); } - public ChatColor getJSONActionBarColor(NotificationType notificationType) - { + public ChatColor getJSONActionBarColor(NotificationType notificationType) { return getChatColor(config.getString("Style.JSON.Notification."+notificationType.toString()+".Color")); }*/ private ChatColor getChatColorFromKey(String keyLocation) { @@ -580,22 +570,19 @@ public class AdvancedConfig extends BukkitConfig { return ChatColor.WHITE; } - /*public boolean isJSONStatHoverElementBold(StatType statType, boolean isPrefix) - { + /*public boolean isJSONStatHoverElementBold(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Bold"; return config.getBoolean(keyLocation); } - public boolean isJSONStatHoverElementItalic(StatType statType, boolean isPrefix) - { + public boolean isJSONStatHoverElementItalic(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Italics"; return config.getBoolean(keyLocation); } - public boolean isJSONStatHoverElementUnderlined(StatType statType, boolean isPrefix) - { + public boolean isJSONStatHoverElementUnderlined(StatType statType, boolean isPrefix) { String keyAddress = isPrefix ? "Prefix" : "Value"; String keyLocation = "Style.JSON.Hover.Details." + StringUtils.getCapitalized(statType.toString()) +"."+keyAddress+".Underline"; return config.getBoolean(keyLocation); diff --git a/src/main/java/com/gmail/nossr50/config/BukkitConfig.java b/src/main/java/com/gmail/nossr50/config/BukkitConfig.java index 23d50b6b2..028a3e3bc 100644 --- a/src/main/java/com/gmail/nossr50/config/BukkitConfig.java +++ b/src/main/java/com/gmail/nossr50/config/BukkitConfig.java @@ -52,7 +52,7 @@ public abstract class BukkitConfig { try { config.save(configFile); - if(copyDefaults && !savedDefaults) { + if (copyDefaults && !savedDefaults) { copyMissingDefaultsFromResource(); savedDefaults = true; } @@ -84,7 +84,7 @@ public abstract class BukkitConfig { YamlConfiguration saveDefaultConfigToDisk() { LogUtils.debug(mcMMO.p.getLogger(), "Copying default config to disk: " + fileName + " to defaults/" + fileName); try(InputStream inputStream = mcMMO.p.getResource(fileName)) { - if(inputStream == null) { + if (inputStream == null) { mcMMO.p.getLogger().severe("Unable to copy default config: " + fileName); return null; } diff --git a/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java b/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java index 6a917b3fd..c9d808e01 100644 --- a/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java +++ b/src/main/java/com/gmail/nossr50/config/LegacyConfigLoader.java @@ -4,31 +4,40 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.LogUtils; import org.bukkit.configuration.file.YamlConfiguration; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.VisibleForTesting; import java.io.File; import java.util.List; @Deprecated public abstract class LegacyConfigLoader { - protected final File configFile; + protected final @NotNull File configFile; protected final @NotNull File dataFolder; - protected String fileName; + protected @NotNull String fileName; protected YamlConfiguration config; - public LegacyConfigLoader(String relativePath, String fileName, @NotNull File dataFolder) { + public LegacyConfigLoader(@NotNull String relativePath, @NotNull String fileName, @NotNull File dataFolder) { this.fileName = fileName; this.dataFolder = dataFolder; configFile = new File(dataFolder, relativePath + File.separator + fileName); loadFile(); } - public LegacyConfigLoader(String fileName, @NotNull File dataFolder) { + public LegacyConfigLoader(@NotNull String fileName, @NotNull File dataFolder) { this.fileName = fileName; this.dataFolder = dataFolder; configFile = new File(dataFolder, fileName); loadFile(); } + @VisibleForTesting + public LegacyConfigLoader(@NotNull File file) { + this.fileName = file.getName(); + this.dataFolder = file.getParentFile(); + configFile = new File(dataFolder, fileName); + loadFile(); + } + @Deprecated public LegacyConfigLoader(String relativePath, String fileName) { this.fileName = fileName; diff --git a/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java b/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java index 7b93ebd89..d92d2778f 100644 --- a/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java +++ b/src/main/java/com/gmail/nossr50/config/WorldBlacklist.java @@ -73,7 +73,7 @@ public class WorldBlacklist { closeRead(fileReader); } - if(blacklist.size() > 0) + if (blacklist.size() > 0) plugin.getLogger().info(blacklist.size() + " entries in mcMMO World Blacklist"); } diff --git a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java index b64e3b62b..4eddee5db 100644 --- a/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java +++ b/src/main/java/com/gmail/nossr50/config/experience/ExperienceConfig.java @@ -467,7 +467,7 @@ public class ExperienceConfig extends BukkitConfig { /* Alchemy */ public double getPotionXP(PotionStage stage) { - return config.getDouble("Experience_Values.Alchemy.Potion_Stage_" + stage.toNumerical(), 10D); + return config.getDouble("Experience_Values.Alchemy.Potion_Brewing.Stage_" + stage.toNumerical(), 10D); } /* Archery */ diff --git a/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java b/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java index 37244835c..99b3b0761 100644 --- a/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java +++ b/src/main/java/com/gmail/nossr50/config/mods/CustomEntityLegacyConfig.java @@ -3,7 +3,6 @@ package com.gmail.nossr50.config.mods; import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.mods.CustomEntity; import com.gmail.nossr50.mcMMO; -import org.apache.commons.lang.ClassUtils; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; @@ -30,7 +29,7 @@ public class CustomEntityLegacyConfig extends LegacyConfigLoader { String className = config.getString(entityName + ".Class", ""); try { - clazz = ClassUtils.getClass(className); + clazz = Class.forName(className); } catch (ClassNotFoundException e) { mcMMO.p.getLogger().warning("Invalid class (" + className + ") detected for " + entityName + "."); mcMMO.p.getLogger().warning("This custom entity may not function properly."); diff --git a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java index 3b21589c6..d0cad88b5 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java +++ b/src/main/java/com/gmail/nossr50/config/skills/alchemy/PotionConfig.java @@ -3,21 +3,29 @@ package com.gmail.nossr50.config.skills.alchemy; import com.gmail.nossr50.config.LegacyConfigLoader; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.ItemUtils; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.*; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.potion.PotionType; +import org.jetbrains.annotations.VisibleForTesting; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.stream.Collectors; + +import static com.gmail.nossr50.util.ItemUtils.setItemName; +import static com.gmail.nossr50.util.PotionUtil.*; public class PotionConfig extends LegacyConfigLoader { - private static PotionConfig instance; private final List concoctionsIngredientsTierOne = new ArrayList<>(); private final List concoctionsIngredientsTierTwo = new ArrayList<>(); @@ -28,30 +36,34 @@ public class PotionConfig extends LegacyConfigLoader { private final List concoctionsIngredientsTierSeven = new ArrayList<>(); private final List concoctionsIngredientsTierEight = new ArrayList<>(); - private final Map potionMap = new HashMap<>(); + /** + * Map of potion names to AlchemyPotion objects. + */ + private final Map alchemyPotions = new HashMap<>(); - private PotionConfig() { + public PotionConfig() { super("potions.yml"); - loadKeys(); } - public static PotionConfig getInstance() { - if (instance == null) { - instance = new PotionConfig(); - } - - return instance; + @VisibleForTesting + PotionConfig(File file) { + super(file); } @Override protected void loadKeys() { + } + + public void loadPotions() { loadConcoctions(); loadPotionMap(); } - private void loadConcoctions() { - ConfigurationSection concoctionSection = config.getConfigurationSection("Concoctions"); + @VisibleForTesting + void loadConcoctions() { + final ConfigurationSection concoctionSection = config.getConfigurationSection("Concoctions"); + // Load the ingredients for each tier loadConcoctionsTier(concoctionsIngredientsTierOne, concoctionSection.getStringList("Tier_One_Ingredients")); loadConcoctionsTier(concoctionsIngredientsTierTwo, concoctionSection.getStringList("Tier_Two_Ingredients")); loadConcoctionsTier(concoctionsIngredientsTierThree, concoctionSection.getStringList("Tier_Three_Ingredients")); @@ -71,7 +83,7 @@ public class PotionConfig extends LegacyConfigLoader { } private void loadConcoctionsTier(List ingredientList, List ingredientStrings) { - if (ingredientStrings != null && ingredientStrings.size() > 0) { + if (ingredientStrings != null && !ingredientStrings.isEmpty()) { for (String ingredientString : ingredientStrings) { ItemStack ingredient = loadIngredient(ingredientString); @@ -85,23 +97,24 @@ public class PotionConfig extends LegacyConfigLoader { /** * Find the Potions configuration section and load all defined potions. */ - private void loadPotionMap() { + int loadPotionMap() { ConfigurationSection potionSection = config.getConfigurationSection("Potions"); - int pass = 0; - int fail = 0; + int potionsLoaded = 0; + int failures = 0; for (String potionName : potionSection.getKeys(false)) { AlchemyPotion potion = loadPotion(potionSection.getConfigurationSection(potionName)); if (potion != null) { - potionMap.put(potionName, potion); - pass++; + alchemyPotions.put(potionName, potion); + potionsLoaded++; } else { - fail++; + failures++; } } - LogUtils.debug(mcMMO.p.getLogger(), "Loaded " + pass + " Alchemy potions, skipped " + fail + "."); + mcMMO.p.getLogger().info("Loaded " + potionsLoaded + " Alchemy potions, skipped " + failures + "."); + return potionsLoaded; } /** @@ -114,37 +127,70 @@ public class PotionConfig extends LegacyConfigLoader { */ private AlchemyPotion loadPotion(ConfigurationSection potion_section) { try { + final String key = potion_section.getName(); + final ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); + boolean extended = false; + boolean upgraded = false; - String name = potion_section.getString("Name"); - if (name != null) { - name = ChatColor.translateAlternateColorCodes('&', name); + if (potionData != null) { + extended = potionData.getBoolean("Extended", false); + upgraded = potionData.getBoolean("Upgraded", false); } - PotionData data; - if (!potion_section.contains("PotionData")) { // Backwards config compatability - short dataValue = Short.parseShort(potion_section.getName()); - Potion potion = Potion.fromDamage(dataValue); - data = new PotionData(potion.getType(), potion.hasExtendedDuration(), potion.getLevel() == 2); + Material material; + final String materialString = potion_section.getString("Material", null); + if (materialString != null) { + material = ItemUtils.exhaustiveMaterialLookup(materialString); + if (material == null) { + mcMMO.p.getLogger().warning("PotionConfig: Failed to parse material for potion " + key + ": " + materialString); + mcMMO.p.getLogger().warning("PotionConfig: Defaulting to POTION"); + material = Material.POTION; + } } else { - ConfigurationSection potionData = potion_section.getConfigurationSection("PotionData"); - data = new PotionData(PotionType.valueOf(potionData.getString("PotionType", "WATER")), potionData.getBoolean("Extended", false), potionData.getBoolean("Upgraded", false)); + mcMMO.p.getLogger().warning("PotionConfig: Missing Material config entry for potion " + key + "," + + " from configuration section: " + potion_section + ", defaulting to POTION"); + material = Material.POTION; } - Material material = Material.POTION; - String mat = potion_section.getString("Material", null); - if (mat != null) { - material = Material.valueOf(mat); + final ItemStack itemStack = new ItemStack(material, 1); + final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); + + if (potionMeta == null) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to get PotionMeta for " + key + ", from configuration section:" + + " " + potion_section); + return null; } - List lore = new ArrayList<>(); + // extended and upgraded seem to be mutually exclusive + if (extended && upgraded) { + mcMMO.p.getLogger().warning("Potion " + key + " has both Extended and Upgraded set to true," + + " defaulting to Extended."); + upgraded = false; + } + + String potionTypeStr = potionData.getString("PotionType", null); + if (potionTypeStr == null) { + mcMMO.p.getLogger().severe("PotionConfig: Missing PotionType for " + key + ", from configuration section:" + + " " + potion_section); + return null; + } + + // This works via side effects + // TODO: Redesign later, side effects are stupid + if(!setPotionType(potionMeta, potionTypeStr, upgraded, extended)) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to set parameters of potion for " + key + ": " + potionTypeStr); + return null; + } + + final List lore = new ArrayList<>(); if (potion_section.contains("Lore")) { for (String line : potion_section.getStringList("Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', line)); } } + potionMeta.setLore(lore); - List effects = new ArrayList<>(); if (potion_section.contains("Effects")) { for (String effect : potion_section.getStringList("Effects")) { String[] parts = effect.split(" "); @@ -154,9 +200,9 @@ public class PotionConfig extends LegacyConfigLoader { int duration = parts.length > 2 ? Integer.parseInt(parts[2]) : 0; if (type != null) { - effects.add(new PotionEffect(type, duration, amplifier)); + potionMeta.addCustomEffect(new PotionEffect(type, duration, amplifier), true); } else { - mcMMO.p.getLogger().warning("Failed to parse effect for potion " + name + ": " + effect); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse effect for potion " + key + ": " + effect); } } } @@ -165,28 +211,62 @@ public class PotionConfig extends LegacyConfigLoader { if (potion_section.contains("Color")) { color = Color.fromRGB(potion_section.getInt("Color")); } else { - color = this.generateColor(effects); + color = this.generateColor(potionMeta.getCustomEffects()); } + potionMeta.setColor(color); - Map children = new HashMap<>(); + final Map children = new HashMap<>(); if (potion_section.contains("Children")) { for (String child : potion_section.getConfigurationSection("Children").getKeys(false)) { ItemStack ingredient = loadIngredient(child); if (ingredient != null) { children.put(ingredient, potion_section.getConfigurationSection("Children").getString(child)); } else { - mcMMO.p.getLogger().warning("Failed to parse child for potion " + name + ": " + child); + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse child for potion " + key + ": " + child); } } } + // Set the name of the potion + setPotionDisplayName(potion_section, potionMeta); - return new AlchemyPotion(material, data, name, lore, effects, color, children); + // TODO: Might not need to .setItemMeta + itemStack.setItemMeta(potionMeta); + return new AlchemyPotion(potion_section.getName(), itemStack, children); } catch (Exception e) { - mcMMO.p.getLogger().warning("Failed to load Alchemy potion: " + potion_section.getName()); + mcMMO.p.getLogger().warning("PotionConfig: Failed to load Alchemy potion: " + potion_section.getName()); + e.printStackTrace(); return null; } } + private boolean setPotionType(PotionMeta potionMeta, String potionTypeStr, boolean upgraded, boolean extended) { + final PotionType potionType = matchPotionType(potionTypeStr, upgraded, extended); + + if (potionType == null) { + mcMMO.p.getLogger().severe("PotionConfig: Failed to parse potion type for: " + potionTypeStr); + return false; + } + + // set base + setBasePotionType(potionMeta, potionType, extended, upgraded); + + // Legacy only + setUpgradedAndExtendedProperties(potionType, potionMeta, upgraded, extended); + return true; + } + + private void setPotionDisplayName(ConfigurationSection section, PotionMeta potionMeta) { + // If a potion doesn't have any custom effects, there is no reason to override the vanilla name + if (potionMeta.getCustomEffects().isEmpty()) { + return; + } + + final String configuredName = section.getString("Name", null); + if (configuredName != null) { + setItemName(potionMeta, configuredName); + } + } + /** * Parse a string representation of an ingredient. * Format: '<MATERIAL>[:data]' @@ -210,43 +290,63 @@ public class PotionConfig extends LegacyConfigLoader { return null; } + /** + * Get the ingredients for the given tier. + * @param tier Tier to get ingredients for. + * @return List of ingredients for the given tier. + */ public List getIngredients(int tier) { - switch (tier) { - case 8: - return concoctionsIngredientsTierEight; - case 7: - return concoctionsIngredientsTierSeven; - case 6: - return concoctionsIngredientsTierSix; - case 5: - return concoctionsIngredientsTierFive; - case 4: - return concoctionsIngredientsTierFour; - case 3: - return concoctionsIngredientsTierThree; - case 2: - return concoctionsIngredientsTierTwo; - case 1: - default: - return concoctionsIngredientsTierOne; - } + return switch (tier) { + case 8 -> concoctionsIngredientsTierEight; + case 7 -> concoctionsIngredientsTierSeven; + case 6 -> concoctionsIngredientsTierSix; + case 5 -> concoctionsIngredientsTierFive; + case 4 -> concoctionsIngredientsTierFour; + case 3 -> concoctionsIngredientsTierThree; + case 2 -> concoctionsIngredientsTierTwo; + default -> concoctionsIngredientsTierOne; + }; } + /** + * Check if the given ItemStack is a valid potion. + * @param item ItemStack to be checked. + * @return True if the given ItemStack is a valid potion, false otherwise. + */ public boolean isValidPotion(ItemStack item) { return getPotion(item) != null; } + /** + * Get the AlchemyPotion that corresponds to the given name. + * @param name Name of the potion to be checked. + * @return AlchemyPotion that corresponds to the given name. + */ public AlchemyPotion getPotion(String name) { - return potionMap.get(name); + return alchemyPotions.get(name); } + /** + * Get the AlchemyPotion that corresponds to the given ItemStack. + * + * @param item ItemStack to be checked. + * + * @return AlchemyPotion that corresponds to the given ItemStack. + */ public AlchemyPotion getPotion(ItemStack item) { - for (AlchemyPotion potion : potionMap.values()) { - if (potion.isSimilar(item)) { - return potion; - } + final List potionList = alchemyPotions.values() + .stream() + .filter(potion -> potion.isSimilarPotion(item)) + .toList(); + if(potionList.size() > 1) { + mcMMO.p.getLogger().severe("Multiple potions defined in config have matched this potion, for mcMMO to behave" + + " properly there should only be one match found."); + mcMMO.p.getLogger().severe("Potion ItemStack:" + item.toString()); + mcMMO.p.getLogger().severe("Alchemy Potions from config matching this item: " + + potionList.stream().map(AlchemyPotion::toString).collect(Collectors.joining(", "))); } - return null; + + return potionList.isEmpty() ? null : potionList.get(0); } public Color generateColor(List effects) { @@ -278,5 +378,4 @@ public class PotionConfig extends LegacyConfigLoader { } return Color.fromRGB(red / colors.size(), green / colors.size(), blue / colors.size()); } - } diff --git a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java index 1a54906a7..491a511ed 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/skills/repair/RepairConfigManager.java @@ -20,7 +20,7 @@ public class RepairConfigManager { repairables.addAll(mainRepairConfig.getLoadedRepairables()); for (String fileName : dataFolder.list()) { - if(fileName.equals(REPAIR_VANILLA_YML)) + if (fileName.equals(REPAIR_VANILLA_YML)) continue; if (!pattern.matcher(fileName).matches()) { diff --git a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java index 77348e8d3..1832da789 100644 --- a/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java +++ b/src/main/java/com/gmail/nossr50/config/skills/salvage/SalvageConfigManager.java @@ -21,7 +21,7 @@ public class SalvageConfigManager { salvageables.addAll(mainSalvageConfig.getLoadedSalvageables()); for (String fileName : dataFolder.list()) { - if(fileName.equals(SALVAGE_VANILLA_YML)) + if (fileName.equals(SALVAGE_VANILLA_YML)) continue; if (!pattern.matcher(fileName).matches()) { diff --git a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java index a02e0bd3f..95788896c 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/FishingTreasureConfig.java @@ -5,6 +5,7 @@ import com.gmail.nossr50.datatypes.treasure.*; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.EnchantmentUtils; import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.PotionUtil; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; @@ -13,12 +14,13 @@ import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; import org.jetbrains.annotations.NotNull; import java.util.*; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; + public class FishingTreasureConfig extends BukkitConfig { public static final String FILENAME = "fishing_treasures.yml"; @@ -48,7 +50,7 @@ public class FishingTreasureConfig extends BukkitConfig { List reason = new ArrayList<>(); ConfigurationSection enchantment_drop_rates = config.getConfigurationSection("Enchantment_Drop_Rates"); - if(enchantment_drop_rates != null) { + if (enchantment_drop_rates != null) { for (String tier : enchantment_drop_rates.getKeys(false)) { double totalEnchantDropRate = 0; double totalItemDropRate = 0; @@ -204,30 +206,40 @@ public class FishingTreasureConfig extends BukkitConfig { } if (materialName.contains("POTION")) { + // Update for 1.20.5 + Material mat = Material.matchMaterial(materialName); if (mat == null) { reason.add("Potion format for " + FILENAME + " has changed"); + continue; } else { item = new ItemStack(mat, amount, data); - PotionMeta itemMeta = (PotionMeta) item.getItemMeta(); + PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); - if (itemMeta == null) { - mcMMO.p.getLogger().severe("Item meta when adding potion to fishing treasure was null, contact the mcMMO devs!"); + if (potionMeta == null) { + mcMMO.p.getLogger().severe("FishingConfig: Item meta when adding potion to fishing treasure was null," + + " contact the mcMMO devs!"); + reason.add("FishingConfig: Item meta when adding potion to fishing treasure was null"); continue; } - PotionType potionType = null; - try { - potionType = PotionType.valueOf(config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); - } catch (IllegalArgumentException ex) { - reason.add("Invalid Potion_Type: " + config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); - } + String potionTypeStr; + potionTypeStr = config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"); boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false); boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false); - itemMeta.setBasePotionData(new PotionData(potionType, extended, upgraded)); + final PotionType potionType = matchPotionType(potionTypeStr, extended, upgraded); + + if (potionType == null) { + reason.add("FishingConfig: Could not derive potion type from: " + potionTypeStr +", " + extended + ", " + upgraded); + continue; + } + + // Set the base potion type + // NOTE: Upgraded/Extended are ignored in 1.20.5 and later + PotionUtil.setBasePotionType(potionMeta, potionType, upgraded, extended); if (customName != null) { - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); + potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', customName)); } if (config.contains(type + "." + treasureName + ".Lore")) { @@ -235,9 +247,9 @@ public class FishingTreasureConfig extends BukkitConfig { for (String s : config.getStringList(type + "." + treasureName + ".Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', s)); } - itemMeta.setLore(lore); + potionMeta.setLore(lore); } - item.setItemMeta(itemMeta); + item.setItemMeta(potionMeta); } } else if (material == Material.ENCHANTED_BOOK) { //If any whitelisted enchants exist we use whitelist-based matching @@ -355,7 +367,8 @@ public class FishingTreasureConfig extends BukkitConfig { Enchantment enchantment = EnchantmentUtils.getByName(enchantmentName); if (enchantment == null) { - mcMMO.p.getLogger().warning("Skipping invalid enchantment in " + FILENAME + ": " + enchantmentName); + mcMMO.p.getLogger().info("Skipping invalid enchantment in '" + FILENAME + "', named:" + + enchantmentName); continue; } diff --git a/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java b/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java index 97967a131..bed8ed059 100755 --- a/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java +++ b/src/main/java/com/gmail/nossr50/config/treasure/TreasureConfig.java @@ -6,6 +6,7 @@ import com.gmail.nossr50.datatypes.treasure.HylianTreasure; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.BlockUtils; import com.gmail.nossr50.util.LogUtils; +import com.gmail.nossr50.util.PotionUtil; import com.gmail.nossr50.util.text.StringUtils; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -14,7 +15,6 @@ import org.bukkit.configuration.ConfigurationSection; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.PotionData; import org.bukkit.potion.PotionType; import java.io.IOException; @@ -165,22 +165,33 @@ public class TreasureConfig extends BukkitConfig { Material mat = Material.matchMaterial(materialName); if (mat == null) { reason.add("Potion format for " + FILENAME + " has changed"); + continue; } else { item = new ItemStack(mat, amount, data); - PotionMeta itemMeta = (PotionMeta) item.getItemMeta(); - - PotionType potionType = null; - try { - potionType = PotionType.valueOf(config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); - } catch (IllegalArgumentException ex) { - reason.add("Invalid Potion_Type: " + config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER")); + PotionMeta potionMeta = (PotionMeta) item.getItemMeta(); + if (potionMeta == null) { + mcMMO.p.getLogger().severe("Item meta when adding potion to treasure was null, contact the mcMMO devs!"); + reason.add("Item meta when adding potion to treasure was null, contact the mcMMO devs!"); + continue; } + + String potionTypeStr; + potionTypeStr = config.getString(type + "." + treasureName + ".PotionData.PotionType", "WATER"); boolean extended = config.getBoolean(type + "." + treasureName + ".PotionData.Extended", false); boolean upgraded = config.getBoolean(type + "." + treasureName + ".PotionData.Upgraded", false); - itemMeta.setBasePotionData(new PotionData(potionType, extended, upgraded)); + PotionType potionType = PotionUtil.matchPotionType(potionTypeStr, extended, upgraded); + + if (potionType == null) { + reason.add("Could not derive potion type from: " + potionTypeStr +", " + extended + ", " + upgraded); + continue; + } + + // Set the base potion type + // NOTE: extended/upgraded are ignored in 1.20.5 and later + PotionUtil.setBasePotionType(potionMeta, potionType, extended, upgraded); if (config.contains(type + "." + treasureName + ".Custom_Name")) { - itemMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name"))); + potionMeta.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getString(type + "." + treasureName + ".Custom_Name"))); } if (config.contains(type + "." + treasureName + ".Lore")) { @@ -188,9 +199,9 @@ public class TreasureConfig extends BukkitConfig { for (String s : config.getStringList(type + "." + treasureName + ".Lore")) { lore.add(ChatColor.translateAlternateColorCodes('&', s)); } - itemMeta.setLore(lore); + potionMeta.setLore(lore); } - item.setItemMeta(itemMeta); + item.setItemMeta(potionMeta); } } else if (material != null) { item = new ItemStack(material, amount, data); diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java index 6f8c397e3..8f68b7bcf 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDataProcessor.java @@ -33,7 +33,7 @@ public class FlatFileDataProcessor { assert !lineData.isEmpty(); //Make sure the data line is "correct" - if(lineData.charAt(lineData.length() - 1) != ':') { + if (lineData.charAt(lineData.length() - 1) != ':') { // Length checks depend on last rawSplitData being ':' // We add it here if it is missing lineData = lineData.concat(":"); @@ -48,9 +48,9 @@ public class FlatFileDataProcessor { boolean anyBadData = false; //This is the minimum size of the split array needed to be considered proper data - if(splitDataLine.length < getMinimumSplitDataLength()) { + if (splitDataLine.length < getMinimumSplitDataLength()) { //Data is considered junk - if(!corruptDataFound) { + if (!corruptDataFound) { logger.severe("Some corrupt data was found in mcmmo.users and has been repaired, it is possible that some player data has been lost in this process."); corruptDataFound = true; } @@ -59,9 +59,9 @@ public class FlatFileDataProcessor { builder.appendFlag(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); //TODO: This block here is probably pointless - if(splitDataLine.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever + if (splitDataLine.length >= 10 //The value here is kind of arbitrary, it shouldn't be too low to avoid false positives, but also we aren't really going to correctly identify when player data has been corrupted or not with 100% accuracy ever && splitDataLine[0] != null && !splitDataLine[0].isEmpty()) { - if(splitDataLine[0].length() <= 16 && splitDataLine[0].length() >= 3) { + if (splitDataLine[0].length() <= 16 && splitDataLine[0].length() >= 3) { logger.severe("Not enough data found to recover corrupted player data for user: "+splitDataLine[0]); registerData(builder.appendFlag(FlatFileDataFlag.TOO_INCOMPLETE)); return; @@ -81,14 +81,14 @@ public class FlatFileDataProcessor { String name = splitDataLine[USERNAME_INDEX]; String strOfUUID = splitDataLine[UUID_INDEX]; - if(name.isEmpty()) { + if (name.isEmpty()) { reportBadDataLine("No name found for data", "[MISSING NAME]", lineData); builder.appendFlag(FlatFileDataFlag.MISSING_NAME); anyBadData = true; badDataValues[USERNAME_INDEX] = true; } - if(strOfUUID.isEmpty() || strOfUUID.equalsIgnoreCase("NULL")) { + if (strOfUUID.isEmpty() || strOfUUID.equalsIgnoreCase("NULL")) { invalidUUID = true; badDataValues[UUID_INDEX] = true; reportBadDataLine("Empty/null UUID for user", "Empty/null", lineData); @@ -110,20 +110,20 @@ public class FlatFileDataProcessor { } //Duplicate UUID is no good, reject them - if(!invalidUUID && uuid != null && uuids.contains(uuid)) { + if (!invalidUUID && uuid != null && uuids.contains(uuid)) { registerData(builder.appendFlag(FlatFileDataFlag.DUPLICATE_UUID)); return; } uuids.add(uuid); - if(names.contains(name)) { + if (names.contains(name)) { builder.appendFlag(FlatFileDataFlag.DUPLICATE_NAME); anyBadData = true; badDataValues[USERNAME_INDEX] = true; } - if(!name.isEmpty()) + if (!name.isEmpty()) names.add(name); //Make sure the data is up to date schema wise, if it isn't we adjust it to the correct size and flag it for repair @@ -136,9 +136,9 @@ public class FlatFileDataProcessor { //Check each data for bad values for(int i = 0; i < DATA_ENTRY_COUNT; i++) { - if(shouldNotBeEmpty(splitDataLine[i], i)) { + if (shouldNotBeEmpty(splitDataLine[i], i)) { - if(i == OVERHAUL_LAST_LOGIN) { + if (i == OVERHAUL_LAST_LOGIN) { builder.appendFlag(FlatFileDataFlag.LAST_LOGIN_SCHEMA_UPGRADE); } @@ -149,13 +149,13 @@ public class FlatFileDataProcessor { boolean isCorrectType = isOfExpectedType(splitDataLine[i], getExpectedValueType(i)); - if(!isCorrectType) { + if (!isCorrectType) { anyBadData = true; badDataValues[i] = true; } } - if(anyBadData) { + if (anyBadData) { builder.appendFlag(FlatFileDataFlag.BAD_VALUES); builder.appendBadDataValues(badDataValues); } @@ -166,7 +166,7 @@ public class FlatFileDataProcessor { public @NotNull String[] isDataSchemaUpToDate(@NotNull String[] splitDataLine, @NotNull FlatFileDataBuilder builder, boolean[] badDataValues) { assert splitDataLine.length <= DATA_ENTRY_COUNT; //should NEVER be higher - if(splitDataLine.length < DATA_ENTRY_COUNT) { + if (splitDataLine.length < DATA_ENTRY_COUNT) { int oldLength = splitDataLine.length; splitDataLine = Arrays.copyOf(splitDataLine, DATA_ENTRY_COUNT); int newLength = splitDataLine.length; @@ -184,7 +184,7 @@ public class FlatFileDataProcessor { public boolean shouldNotBeEmpty(@Nullable String data, int index) { - if(getExpectedValueType(index) == ExpectedType.IGNORED) { + if (getExpectedValueType(index) == ExpectedType.IGNORED) { return false; } else { return data == null || data.isEmpty(); @@ -248,73 +248,31 @@ public class FlatFileDataProcessor { FlatFileDataContainer flatFileDataContainer = builder.build(); flatFileDataContainers.add(flatFileDataContainer); - if(flatFileDataContainer.getDataFlags() != null) + if (flatFileDataContainer.getDataFlags() != null) flatFileDataFlags.addAll(flatFileDataContainer.getDataFlags()); } public static @NotNull ExpectedType getExpectedValueType(int dataIndex) throws IndexOutOfBoundsException { - switch(dataIndex) { - case USERNAME_INDEX: - return ExpectedType.STRING; - case 2: //Assumption: Used to be for something, no longer used - case 3: //Assumption: Used to be for something, no longer used - case 23: //Assumption: Used to be used for something, no longer used - case 33: //Assumption: Used to be used for something, no longer used - case HEALTHBAR: - case LEGACY_LAST_LOGIN: - return ExpectedType.IGNORED; - case SKILLS_MINING: - case SKILLS_REPAIR: - case SKILLS_UNARMED: - case SKILLS_HERBALISM: - case SKILLS_EXCAVATION: - case SKILLS_ARCHERY: - case SKILLS_SWORDS: - case SKILLS_AXES: - case SKILLS_WOODCUTTING: - case SKILLS_ACROBATICS: - case SKILLS_TAMING: - case SKILLS_FISHING: - case SKILLS_ALCHEMY: - case SKILLS_CROSSBOWS: - case SKILLS_TRIDENTS: - case COOLDOWN_BERSERK: - case COOLDOWN_GIGA_DRILL_BREAKER: - case COOLDOWN_TREE_FELLER: - case COOLDOWN_GREEN_TERRA: - case COOLDOWN_SERRATED_STRIKES: - case COOLDOWN_SKULL_SPLITTER: - case COOLDOWN_SUPER_BREAKER: - case COOLDOWN_BLAST_MINING: - case SCOREBOARD_TIPS: - case COOLDOWN_CHIMAERA_WING: - case COOLDOWN_SUPER_SHOTGUN: - case COOLDOWN_TRIDENTS: - case COOLDOWN_ARCHERY: - return ExpectedType.INTEGER; - case EXP_MINING: - case EXP_WOODCUTTING: - case EXP_REPAIR: - case EXP_UNARMED: - case EXP_HERBALISM: - case EXP_EXCAVATION: - case EXP_ARCHERY: - case EXP_SWORDS: - case EXP_AXES: - case EXP_ACROBATICS: - case EXP_TAMING: - case EXP_FISHING: - case EXP_ALCHEMY: - case EXP_CROSSBOWS: - case EXP_TRIDENTS: - return ExpectedType.FLOAT; - case UUID_INDEX: - return ExpectedType.UUID; - case OVERHAUL_LAST_LOGIN: - return ExpectedType.LONG; - } - - throw new IndexOutOfBoundsException(); + return switch (dataIndex) { + case USERNAME_INDEX -> ExpectedType.STRING; //Assumption: Used to be for something, no longer used + //Assumption: Used to be for something, no longer used + //Assumption: Used to be used for something, no longer used + //Assumption: Used to be used for something, no longer used + case 2, 3, 23, 33, HEALTHBAR, LEGACY_LAST_LOGIN -> ExpectedType.IGNORED; + case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, SKILLS_ARCHERY, + SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, SKILLS_FISHING, + SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES, COOLDOWN_BERSERK, + COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, COOLDOWN_SERRATED_STRIKES, + COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, SCOREBOARD_TIPS, + COOLDOWN_CHIMAERA_WING, COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES -> + ExpectedType.INTEGER; + case EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, EXP_EXCAVATION, EXP_ARCHERY, + EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, EXP_CROSSBOWS, + EXP_TRIDENTS, EXP_MACES -> ExpectedType.FLOAT; + case UUID_INDEX -> ExpectedType.UUID; + case OVERHAUL_LAST_LOGIN -> ExpectedType.LONG; + default -> throw new IndexOutOfBoundsException(); + }; } public @NotNull List getFlatFileDataContainers() { @@ -337,12 +295,12 @@ public class FlatFileDataProcessor { for(FlatFileDataContainer dataContainer : flatFileDataContainers) { String[] splitData = FlatFileDataUtil.getPreparedSaveDataLine(dataContainer); - if(splitData == null) + if (splitData == null) continue; //We add a trailing : as it is needed for some reason (is it?) //TODO: Is the trailing ":" actually necessary? - String fromSplit = org.apache.commons.lang.StringUtils.join(splitData, ":") + ":"; + String fromSplit = org.apache.commons.lang3.StringUtils.join(splitData, ":") + ":"; stringBuilder.append(fromSplit).append("\r\n"); } diff --git a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java index d4d2e51b6..a73be51ad 100644 --- a/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/FlatFileDatabaseManager.java @@ -87,8 +87,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager { public static final int COOLDOWN_SUPER_SHOTGUN = 49; public static final int COOLDOWN_TRIDENTS = 50; public static final int COOLDOWN_ARCHERY = 51; + public static final int EXP_MACES = 52; + public static final int SKILLS_MACES = 53; + public static final int COOLDOWN_MACES = 54; //Update this everytime new data is added - public static final int DATA_ENTRY_COUNT = COOLDOWN_ARCHERY + 1; + public static final int DATA_ENTRY_COUNT = COOLDOWN_MACES + 1; FlatFileDatabaseManager(@NotNull File usersFile, @NotNull Logger logger, long purgeTime, int startingLevel, boolean testing) { this.usersFile = usersFile; @@ -98,15 +101,15 @@ public final class FlatFileDatabaseManager implements DatabaseManager { this.startingLevel = startingLevel; this.testing = testing; - if(!usersFile.exists()) { + if (!usersFile.exists()) { initEmptyDB(); } - if(!testing) { + if (!testing) { List flatFileDataFlags = checkFileHealthAndStructure(); - if(flatFileDataFlags != null) { - if(!flatFileDataFlags.isEmpty()) { + if (flatFileDataFlags != null) { + if (!flatFileDataFlags.isEmpty()) { logger.info("Detected "+flatFileDataFlags.size() + " data entries which need correction."); } } @@ -149,8 +152,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { // If they're still around, rewrite them to the file. if (!powerless) { writer.append(line).append("\r\n"); - } - else { + } else { purgedUsers++; } } @@ -219,7 +221,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (lastPlayed == -1) { OfflinePlayer player = mcMMO.p.getServer().getOfflinePlayer(uuid); - if(player.getLastPlayed() != 0) { + if (player.getLastPlayed() != 0) { lastPlayed = player.getLastPlayed(); rewrite = true; } @@ -231,7 +233,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { if (rewrite) { // Rewrite their data with a valid time character[OVERHAUL_LAST_LOGIN] = Long.toString(lastPlayed); - String newLine = org.apache.commons.lang.StringUtils.join(character, ":"); + String newLine = org.apache.commons.lang3.StringUtils.join(character, ":"); writer.append(newLine).append("\r\n"); } else { writer.append(line).append("\r\n"); @@ -243,7 +245,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { out = new FileWriter(usersFilePath); out.write(writer.toString()); - if(testing) { + if (testing) { System.out.println(writer); } } @@ -351,15 +353,15 @@ public final class FlatFileDatabaseManager implements DatabaseManager { boolean wroteUser = false; // While not at the end of the file while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { writer.append(line).append("\r\n"); continue; } //Check for incomplete or corrupted data - if(!line.contains(":")) { + if (!line.contains(":")) { - if(!corruptDataFound) { + if (!corruptDataFound) { logger.severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); corruptDataFound = true; } @@ -370,9 +372,9 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String[] splitData = line.split(":"); //This would be rare, but check the splitData for having enough entries to contain a UUID - if(splitData.length < UUID_INDEX) { //UUID have been in mcMMO DB for a very long time so any user without + if (splitData.length < UUID_INDEX) { //UUID have been in mcMMO DB for a very long time so any user without - if(!corruptDataFound) { + if (!corruptDataFound) { logger.severe("mcMMO found some unexpected or corrupted data in mcmmo.users and is removing it, it is possible some data has been lost."); corruptDataFound = true; } @@ -394,7 +396,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { /* * If we couldn't find the user in the DB we need to add him */ - if(!wroteUser) { + if (!wroteUser) { writeUserToLine(profile, writer); } @@ -478,12 +480,24 @@ public final class FlatFileDatabaseManager implements DatabaseManager { appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.CROSSBOWS))).append(":"); appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.TRIDENTS))).append(":"); appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.TRIDENTS))).append(":"); + // public static final int COOLDOWN_SUPER_SHOTGUN = 49; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN))).append(":"); + // public static final int COOLDOWN_TRIDENTS = 50; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.TRIDENTS_SUPER_ABILITY))).append(":"); + // public static final int COOLDOWN_ARCHERY = 51; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.EXPLOSIVE_SHOT))).append(":"); + // public static final int EXP_MACES = 52; + appendable.append(String.valueOf(profile.getSkillXpLevel(PrimarySkillType.MACES))).append(":"); + // public static final int SKILLS_MACES = 53; + appendable.append(String.valueOf(profile.getSkillLevel(PrimarySkillType.MACES))).append(":"); + // public static final int COOLDOWN_MACES = 54; + appendable.append(String.valueOf(profile.getAbilityDATS(SuperAbilityType.MACES_SUPER_ABILITY))).append(":"); appendable.append("\r\n"); } public @NotNull List readLeaderboard(@Nullable PrimarySkillType primarySkillType, int pageNumber, int statsPerPage) throws InvalidSkillException { //Fix for a plugin that people are using that is throwing SQL errors - if(primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) { + if (primarySkillType != null && SkillTools.isChildSkill(primarySkillType)) { logger.severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } @@ -557,11 +571,11 @@ public final class FlatFileDatabaseManager implements DatabaseManager { private @NotNull UserQuery getUserQuery(@Nullable UUID uuid, @Nullable String playerName) throws NullPointerException { boolean hasName = playerName != null && !playerName.equalsIgnoreCase("null"); - if(hasName && uuid != null) { + if (hasName && uuid != null) { return new UserQueryFull(playerName, uuid); } else if (uuid != null) { return new UserQueryUUIDImpl(uuid); - } else if(hasName) { + } else if (hasName) { return new UserQueryNameImpl(playerName); } else { throw new NullPointerException("Both name and UUID cannot be null, at least one must be non-null!"); @@ -595,7 +609,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } @@ -605,12 +619,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { /* Don't read corrupt data */ - if(rawSplitData.length < (USERNAME_INDEX + 1)) { + if (rawSplitData.length < (USERNAME_INDEX + 1)) { continue; } // we found the player - if(playerName.equalsIgnoreCase(rawSplitData[USERNAME_INDEX])) { + if (playerName.equalsIgnoreCase(rawSplitData[USERNAME_INDEX])) { return loadFromLine(rawSplitData); } } @@ -645,24 +659,24 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String line; while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } // Find if the line contains the player we want. String[] rawSplitData = line.split(":"); /* Don't read corrupt data */ - if(rawSplitData.length < (UUID_INDEX + 1)) { + if (rawSplitData.length < (UUID_INDEX + 1)) { continue; } try { UUID fromDataUUID = UUID.fromString(rawSplitData[UUID_INDEX]); - if(fromDataUUID.equals(uuid)) { + if (fromDataUUID.equals(uuid)) { return loadFromLine(rawSplitData); } } catch (Exception e) { - if(testing) { + if (testing) { e.printStackTrace(); } } @@ -701,20 +715,20 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String line; while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } // Find if the line contains the player we want. String[] rawSplitData = line.split(":"); /* Don't read corrupt data */ - if(rawSplitData.length < (UUID_INDEX + 1)) { + if (rawSplitData.length < (UUID_INDEX + 1)) { continue; } try { UUID fromDataUUID = UUID.fromString(rawSplitData[UUID_INDEX]); - if(fromDataUUID.equals(uuid)) { + if (fromDataUUID.equals(uuid)) { //Matched UUID, now check if name matches String dbPlayerName = rawSplitData[USERNAME_INDEX]; @@ -731,7 +745,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { return loadFromLine(rawSplitData); } } catch (Exception e) { - if(testing) { + if (testing) { e.printStackTrace(); } } @@ -759,7 +773,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } private @NotNull PlayerProfile grabUnloadedProfile(@NotNull UUID uuid, @Nullable String playerName) { - if(playerName == null) { + if (playerName == null) { playerName = ""; //No name for you boy! } @@ -778,7 +792,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { String line; while ((line = in.readLine()) != null) { - if(line.startsWith("#")) { + if (line.startsWith("#")) { continue; } @@ -890,7 +904,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } character[UUID_INDEX] = fetchedUUIDs.remove(character[USERNAME_INDEX]).toString(); - line = org.apache.commons.lang.StringUtils.join(character, ":") + ":"; + line = org.apache.commons.lang3.StringUtils.join(character, ":") + ":"; } i++; @@ -987,6 +1001,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { List alchemy = new ArrayList<>(); List crossbows = new ArrayList<>(); List tridents = new ArrayList<>(); + List maces = new ArrayList<>(); BufferedReader in = null; String playerName = null; @@ -998,7 +1013,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { while ((line = in.readLine()) != null) { - if(line.startsWith("#")) + if (line.startsWith("#")) continue; String[] data = line.split(":"); @@ -1022,6 +1037,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { powerLevel += putStat(woodcutting, playerName, skills.get(PrimarySkillType.WOODCUTTING)); powerLevel += putStat(crossbows, playerName, skills.get(PrimarySkillType.CROSSBOWS)); powerLevel += putStat(tridents, playerName, skills.get(PrimarySkillType.TRIDENTS)); + powerLevel += putStat(maces, playerName, skills.get(PrimarySkillType.MACES)); putStat(powerLevels, playerName, powerLevel); } @@ -1059,6 +1075,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { alchemy.sort(c); crossbows.sort(c); tridents.sort(c); + maces.sort(c); powerLevels.sort(c); playerStatHash.put(PrimarySkillType.MINING, mining); @@ -1076,6 +1093,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { playerStatHash.put(PrimarySkillType.ALCHEMY, alchemy); playerStatHash.put(PrimarySkillType.CROSSBOWS, crossbows); playerStatHash.put(PrimarySkillType.TRIDENTS, tridents); + playerStatHash.put(PrimarySkillType.MACES, maces); return LeaderboardStatus.UPDATED; } @@ -1126,12 +1144,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { //Analyze the data while ((currentLine = bufferedReader.readLine()) != null) { //Commented lines - if(currentLine.startsWith("#") && dbCommentDate == null) { //The first commented line in the file is likely to be our note about when the file was created + if (currentLine.startsWith("#") && dbCommentDate == null) { //The first commented line in the file is likely to be our note about when the file was created dbCommentDate = currentLine; continue; } - if(currentLine.isEmpty()) + if (currentLine.isEmpty()) continue; //TODO: We are never passing empty lines, should we remove the flag for them? @@ -1139,12 +1157,12 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } //Only update the file if needed - if(!dataProcessor.getFlatFileDataFlags().isEmpty()) { + if (!dataProcessor.getFlatFileDataFlags().isEmpty()) { flagsFound = new ArrayList<>(dataProcessor.getFlatFileDataFlags()); logger.info("Updating FlatFile Database..."); fileWriter = new FileWriter(usersFilePath); //Write data to file - if(dbCommentDate != null) + if (dbCommentDate != null) fileWriter.write(dbCommentDate + "\r\n"); fileWriter.write(dataProcessor.processDataForSave().toString()); @@ -1157,7 +1175,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } } - if(flagsFound == null || flagsFound.isEmpty()) { + if (flagsFound == null || flagsFound.isEmpty()) { return null; } else { return flagsFound; @@ -1165,7 +1183,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { } private void closeResources(BufferedReader bufferedReader, FileWriter fileWriter) { - if(bufferedReader != null) { + if (bufferedReader != null) { try { bufferedReader.close(); } @@ -1239,6 +1257,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.ALCHEMY, EXP_ALCHEMY, username); tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.CROSSBOWS, EXP_CROSSBOWS, username); tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.TRIDENTS, EXP_TRIDENTS, username); + tryLoadSkillFloatValuesFromRawData(skillsXp, character, PrimarySkillType.MACES, EXP_MACES, username); // Taming - Unused tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_BREAKER, COOLDOWN_SUPER_BREAKER, username); @@ -1254,6 +1273,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.BLAST_MINING, COOLDOWN_BLAST_MINING, username); tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.SUPER_SHOTGUN, COOLDOWN_SUPER_SHOTGUN, username); tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.TRIDENTS_SUPER_ABILITY, COOLDOWN_TRIDENTS, username); + tryLoadSkillCooldownFromRawData(skillsDATS, character, SuperAbilityType.MACES_SUPER_ABILITY, COOLDOWN_MACES, username); UUID uuid; try { @@ -1343,6 +1363,7 @@ public final class FlatFileDatabaseManager implements DatabaseManager { tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.ALCHEMY, SKILLS_ALCHEMY, username); tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.CROSSBOWS, SKILLS_CROSSBOWS, username); tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.TRIDENTS, SKILLS_TRIDENTS, username); + tryLoadSkillIntValuesFromRawData(skills, character, PrimarySkillType.MACES, SKILLS_MACES, username); return skills; } diff --git a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java index 892a43721..aef90e48c 100644 --- a/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java +++ b/src/main/java/com/gmail/nossr50/database/SQLDatabaseManager.java @@ -59,7 +59,7 @@ public final class SQLDatabaseManager implements DatabaseManager { this.h2 = h2; String connectionString = getConnectionString(h2); - if(!h2 && mcMMO.p.getGeneralConfig().getMySQLPublicKeyRetrieval()) { + if (!h2 && mcMMO.p.getGeneralConfig().getMySQLPublicKeyRetrieval()) { connectionString+= "&allowPublicKeyRetrieval=true"; } @@ -140,7 +140,7 @@ public final class SQLDatabaseManager implements DatabaseManager { String connectionString = "jdbc:mysql://" + mcMMO.p.getGeneralConfig().getMySQLServerName() + ":" + mcMMO.p.getGeneralConfig().getMySQLServerPort() + "/" + mcMMO.p.getGeneralConfig().getMySQLDatabaseName(); - if(!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) //Temporary hack for SQL and 1.17 support + if (!mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 17, 0) //Temporary hack for SQL and 1.17 support && mcMMO.p.getGeneralConfig().getMySQLSSL()) connectionString += "?verifyServerCertificate=false"+ @@ -169,7 +169,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + "taming = 0 AND mining = 0 AND woodcutting = 0 AND repair = 0 " + "AND unarmed = 0 AND herbalism = 0 AND excavation = 0 AND " + "archery = 0 AND swords = 0 AND axes = 0 AND acrobatics = 0 " - + "AND fishing = 0 AND alchemy = 0 AND crossbows = 0 AND tridents = 0;"); + + "AND fishing = 0 AND alchemy = 0 AND crossbows = 0 AND tridents = 0 AND maces = 0;"); statement.executeUpdate("DELETE FROM `" + tablePrefix + "experience` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "experience`.`user_id` = `s`.`user_id`)"); statement.executeUpdate("DELETE FROM `" + tablePrefix + "huds` WHERE NOT EXISTS (SELECT * FROM `" + tablePrefix + "skills` `s` WHERE `" + tablePrefix + "huds`.`user_id` = `s`.`user_id`)"); @@ -247,7 +247,7 @@ public final class SQLDatabaseManager implements DatabaseManager { } if (success) { - if(uuid != null) + if (uuid != null) cleanupUser(uuid); Misc.profileCleanup(playerName); @@ -291,7 +291,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + " taming = ?, mining = ?, repair = ?, woodcutting = ?" + ", unarmed = ?, herbalism = ?, excavation = ?" + ", archery = ?, swords = ?, axes = ?, acrobatics = ?" - + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ?, total = ? WHERE user_id = ?"); + + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ?, maces = ?, total = ? WHERE user_id = ?"); statement.setInt(1, profile.getSkillLevel(PrimarySkillType.TAMING)); statement.setInt(2, profile.getSkillLevel(PrimarySkillType.MINING)); statement.setInt(3, profile.getSkillLevel(PrimarySkillType.REPAIR)); @@ -307,11 +307,12 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setInt(13, profile.getSkillLevel(PrimarySkillType.ALCHEMY)); statement.setInt(14, profile.getSkillLevel(PrimarySkillType.CROSSBOWS)); statement.setInt(15, profile.getSkillLevel(PrimarySkillType.TRIDENTS)); + statement.setInt(16, profile.getSkillLevel(PrimarySkillType.MACES)); int total = 0; for (PrimarySkillType primarySkillType : SkillTools.NON_CHILD_SKILLS) total += profile.getSkillLevel(primarySkillType); - statement.setInt(16, total); - statement.setInt(17, id); + statement.setInt(17, total); + statement.setInt(18, id); success &= (statement.executeUpdate() != 0); statement.close(); if (!success) { @@ -323,7 +324,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + " taming = ?, mining = ?, repair = ?, woodcutting = ?" + ", unarmed = ?, herbalism = ?, excavation = ?" + ", archery = ?, swords = ?, axes = ?, acrobatics = ?" - + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ? WHERE user_id = ?"); + + ", fishing = ?, alchemy = ?, crossbows = ?, tridents = ?, maces = ? WHERE user_id = ?"); statement.setInt(1, profile.getSkillXpLevel(PrimarySkillType.TAMING)); statement.setInt(2, profile.getSkillXpLevel(PrimarySkillType.MINING)); statement.setInt(3, profile.getSkillXpLevel(PrimarySkillType.REPAIR)); @@ -339,7 +340,8 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setInt(13, profile.getSkillXpLevel(PrimarySkillType.ALCHEMY)); statement.setInt(14, profile.getSkillXpLevel(PrimarySkillType.CROSSBOWS)); statement.setInt(15, profile.getSkillXpLevel(PrimarySkillType.TRIDENTS)); - statement.setInt(16, id); + statement.setInt(16, profile.getSkillXpLevel(PrimarySkillType.MACES)); + statement.setInt(17, id); success &= (statement.executeUpdate() != 0); statement.close(); if (!success) { @@ -350,7 +352,8 @@ public final class SQLDatabaseManager implements DatabaseManager { statement = connection.prepareStatement("UPDATE " + tablePrefix + "cooldowns SET " + " mining = ?, woodcutting = ?, unarmed = ?" + ", herbalism = ?, excavation = ?, swords = ?" - + ", axes = ?, blast_mining = ?, chimaera_wing = ?, crossbows = ?, tridents = ? WHERE user_id = ?"); + + ", axes = ?, blast_mining = ?, chimaera_wing = ?, crossbows = ?" + + ", tridents = ?, maces = ? WHERE user_id = ?"); statement.setLong(1, profile.getAbilityDATS(SuperAbilityType.SUPER_BREAKER)); statement.setLong(2, profile.getAbilityDATS(SuperAbilityType.TREE_FELLER)); statement.setLong(3, profile.getAbilityDATS(SuperAbilityType.BERSERK)); @@ -362,7 +365,8 @@ public final class SQLDatabaseManager implements DatabaseManager { statement.setLong(9, profile.getUniqueData(UniqueDataType.CHIMAERA_WING_DATS)); statement.setLong(10, profile.getAbilityDATS(SuperAbilityType.SUPER_SHOTGUN)); statement.setLong(11, profile.getAbilityDATS(SuperAbilityType.TRIDENTS_SUPER_ABILITY)); - statement.setInt(12, id); + statement.setLong(12, profile.getAbilityDATS(SuperAbilityType.MACES_SUPER_ABILITY)); + statement.setInt(13, id); success = (statement.executeUpdate() != 0); statement.close(); if (!success) { @@ -396,7 +400,7 @@ public final class SQLDatabaseManager implements DatabaseManager { List stats = new ArrayList<>(); //Fix for a plugin that people are using that is throwing SQL errors - if(skill != null && SkillTools.isChildSkill(skill)) { + if (skill != null && SkillTools.isChildSkill(skill)) { logger.severe("A plugin hooking into mcMMO is being naughty with our database commands, update all plugins that hook into mcMMO and contact their devs!"); throw new InvalidSkillException("A plugin hooking into mcMMO that you are using is attempting to read leaderboard skills for child skills, child skills do not have leaderboards! This is NOT an mcMMO error!"); } @@ -627,7 +631,7 @@ public final class SQLDatabaseManager implements DatabaseManager { } private PlayerProfile loadPlayerFromDB(@Nullable UUID uuid, @Nullable String playerName) throws RuntimeException { - if(uuid == null && playerName == null) { + if (uuid == null && playerName == null) { throw new RuntimeException("Error looking up player, both UUID and playerName are null and one must not be."); } @@ -648,9 +652,9 @@ public final class SQLDatabaseManager implements DatabaseManager { statement = connection.prepareStatement( "SELECT " + - "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.crossbows, s.tridents, " + - "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.crossbows, e.tridents, " + - "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.crossbows, c.tridents, " + + "s.taming, s.mining, s.repair, s.woodcutting, s.unarmed, s.herbalism, s.excavation, s.archery, s.swords, s.axes, s.acrobatics, s.fishing, s.alchemy, s.crossbows, s.tridents, s.maces, " + + "e.taming, e.mining, e.repair, e.woodcutting, e.unarmed, e.herbalism, e.excavation, e.archery, e.swords, e.axes, e.acrobatics, e.fishing, e.alchemy, e.crossbows, e.tridents, e.maces, " + + "c.taming, c.mining, c.repair, c.woodcutting, c.unarmed, c.herbalism, c.excavation, c.archery, c.swords, c.axes, c.acrobatics, c.blast_mining, c.chimaera_wing, c.crossbows, c.tridents, c.maces, " + "h.mobhealthbar, h.scoreboardtips, u.uuid, u.`user` " + "FROM " + tablePrefix + "users u " + "JOIN " + tablePrefix + "skills s ON (u.id = s.user_id) " @@ -922,6 +926,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + "`chimaera_wing` int(32) unsigned NOT NULL DEFAULT '0'," + "`crossbows` int(32) unsigned NOT NULL DEFAULT '0'," + "`tridents` int(32) unsigned NOT NULL DEFAULT '0'," + + "`maces` int(32) unsigned NOT NULL DEFAULT '0'," + "PRIMARY KEY (`user_id`)) " + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); tryClose(createStatement); @@ -950,6 +955,7 @@ public final class SQLDatabaseManager implements DatabaseManager { + "`alchemy` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + "`crossbows` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + "`tridents` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + + "`maces` int(10) unsigned NOT NULL DEFAULT "+startingLevel+"," + "`total` int(10) unsigned NOT NULL DEFAULT "+totalLevel+"," + "PRIMARY KEY (`user_id`)) " + "DEFAULT CHARSET=" + CHARSET_SQL + ";"); @@ -1017,20 +1023,24 @@ public final class SQLDatabaseManager implements DatabaseManager { tryClose(connection); } - String skills = "skills"; - String crossbows = "crossbows"; - String tridents = "tridents"; - String experience = "experience"; - String cooldowns = "cooldowns"; + final String skills = "skills"; + final String crossbows = "crossbows"; + final String tridents = "tridents"; + final String maces = "maces"; + final String experience = "experience"; + final String cooldowns = "cooldowns"; updateStructure(skills, crossbows, String.valueOf(32)); updateStructure(skills, tridents, String.valueOf(32)); + updateStructure(skills, maces, String.valueOf(32)); updateStructure(experience, crossbows, String.valueOf(10)); updateStructure(experience, tridents, String.valueOf(10)); + updateStructure(experience, maces, String.valueOf(10)); updateStructure(cooldowns, crossbows, String.valueOf(10)); updateStructure(cooldowns, tridents, String.valueOf(10)); + updateStructure(cooldowns, maces, String.valueOf(10)); } private void updateStructure(String tableName, String columnName, String columnSize) { @@ -1213,15 +1223,14 @@ public final class SQLDatabaseManager implements DatabaseManager { Map skillsXp = new EnumMap<>(PrimarySkillType.class); // Skill & XP Map skillsDATS = new EnumMap<>(SuperAbilityType.class); // Ability & Cooldown Map uniqueData = new EnumMap<>(UniqueDataType.class); //Chimaera wing cooldown and other misc info - MobHealthbarType mobHealthbarType; UUID uuid; int scoreboardTipsShown; final int OFFSET_SKILLS = 0; // TODO update these numbers when the query // changes (a new skill is added) - final int OFFSET_XP = 15; - final int OFFSET_DATS = 28; - final int OFFSET_OTHER = 41; + final int OFFSET_XP = 16; + final int OFFSET_DATS = 29; + final int OFFSET_OTHER = 42; skills.put(PrimarySkillType.TAMING, result.getInt(OFFSET_SKILLS + 1)); skills.put(PrimarySkillType.MINING, result.getInt(OFFSET_SKILLS + 2)); @@ -1238,6 +1247,7 @@ public final class SQLDatabaseManager implements DatabaseManager { skills.put(PrimarySkillType.ALCHEMY, result.getInt(OFFSET_SKILLS + 13)); skills.put(PrimarySkillType.CROSSBOWS, result.getInt(OFFSET_SKILLS + 14)); skills.put(PrimarySkillType.TRIDENTS, result.getInt(OFFSET_SKILLS + 15)); + skills.put(PrimarySkillType.MACES, result.getInt(OFFSET_SKILLS + 16)); skillsXp.put(PrimarySkillType.TAMING, result.getFloat(OFFSET_XP + 1)); skillsXp.put(PrimarySkillType.MINING, result.getFloat(OFFSET_XP + 2)); @@ -1254,6 +1264,7 @@ public final class SQLDatabaseManager implements DatabaseManager { skillsXp.put(PrimarySkillType.ALCHEMY, result.getFloat(OFFSET_XP + 13)); skillsXp.put(PrimarySkillType.CROSSBOWS, result.getFloat(OFFSET_XP + 14)); skillsXp.put(PrimarySkillType.TRIDENTS, result.getFloat(OFFSET_XP + 15)); + skillsXp.put(PrimarySkillType.MACES, result.getFloat(OFFSET_XP + 16)); // Taming - Unused - result.getInt(OFFSET_DATS + 1) skillsDATS.put(SuperAbilityType.SUPER_BREAKER, result.getInt(OFFSET_DATS + 2)); @@ -1262,6 +1273,7 @@ public final class SQLDatabaseManager implements DatabaseManager { skillsDATS.put(SuperAbilityType.BERSERK, result.getInt(OFFSET_DATS + 5)); skillsDATS.put(SuperAbilityType.GREEN_TERRA, result.getInt(OFFSET_DATS + 6)); skillsDATS.put(SuperAbilityType.GIGA_DRILL_BREAKER, result.getInt(OFFSET_DATS + 7)); + skillsDATS.put(SuperAbilityType.EXPLOSIVE_SHOT, result.getInt(OFFSET_DATS + 8)); // Archery - Unused - result.getInt(OFFSET_DATS + 8) skillsDATS.put(SuperAbilityType.SERRATED_STRIKES, result.getInt(OFFSET_DATS + 9)); skillsDATS.put(SuperAbilityType.SKULL_SPLITTER, result.getInt(OFFSET_DATS + 10)); @@ -1270,6 +1282,7 @@ public final class SQLDatabaseManager implements DatabaseManager { uniqueData.put(UniqueDataType.CHIMAERA_WING_DATS, result.getInt(OFFSET_DATS + 13)); skillsDATS.put(SuperAbilityType.SUPER_SHOTGUN, result.getInt(OFFSET_DATS + 14)); skillsDATS.put(SuperAbilityType.TRIDENTS_SUPER_ABILITY, result.getInt(OFFSET_DATS + 15)); + skillsDATS.put(SuperAbilityType.MACES_SUPER_ABILITY, result.getInt(OFFSET_DATS + 16)); try { scoreboardTipsShown = result.getInt(OFFSET_OTHER + 2); diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java index ed048d5e1..eb6e3dd2a 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataBuilder.java @@ -28,7 +28,7 @@ public class FlatFileDataBuilder { } public @NotNull FlatFileDataContainer build() { - if(dataFlags.contains(FlatFileDataFlag.BAD_VALUES)) { + if (dataFlags.contains(FlatFileDataFlag.BAD_VALUES)) { return new BadCategorizedFlatFileData(uniqueProcessingId, dataFlags, splitStringData, badDataValues); } diff --git a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java index 285c501fd..a3c78685f 100644 --- a/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java +++ b/src/main/java/com/gmail/nossr50/database/flatfile/FlatFileDataUtil.java @@ -10,14 +10,14 @@ import static com.gmail.nossr50.database.FlatFileDatabaseManager.*; public class FlatFileDataUtil { public static @Nullable String[] getPreparedSaveDataLine(@NotNull FlatFileDataContainer dataContainer) { - if(dataContainer.getDataFlags() == null) { + if (dataContainer.getDataFlags() == null) { return dataContainer.getSplitData(); } //Data of this type is not salvageable //TODO: Test that we ignore the things we are supposed to ignore //TODO: Should we even keep track of the bad data or just not even build data containers for it? Making containers for it is only really useful for debugging.. well I suppose operations are typically async so it shouldn't matter - if(dataContainer.getDataFlags().contains(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE) + if (dataContainer.getDataFlags().contains(FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE) || dataContainer.getDataFlags().contains(FlatFileDataFlag.DUPLICATE_UUID) //For now we will not try to fix any issues with UUIDs || dataContainer.getDataFlags().contains(FlatFileDataFlag.BAD_UUID_DATA) //For now we will not try to fix any issues with UUIDs || dataContainer.getDataFlags().contains(FlatFileDataFlag.TOO_INCOMPLETE)) { @@ -29,7 +29,7 @@ public class FlatFileDataUtil { /* * First fix the bad data values if they exist */ - if(dataContainer instanceof BadCategorizedFlatFileData badData) { + if (dataContainer instanceof BadCategorizedFlatFileData badData) { splitData = repairBadData(dataContainer.getSplitData(), badData.getBadDataIndexes()); } else { splitData = dataContainer.getSplitData(); @@ -42,7 +42,7 @@ public class FlatFileDataUtil { public static @NotNull String[] repairBadData(@NotNull String[] splitData, boolean[] badDataValues) { for(int i = 0; i < FlatFileDatabaseManager.DATA_ENTRY_COUNT; i++) { - if(badDataValues[i]) { + if (badDataValues[i]) { //This data value was marked as bad so we zero initialize it splitData[i] = getZeroInitialisedData(i, 0); } @@ -56,67 +56,29 @@ public class FlatFileDataUtil { * @return the "zero" initialized data corresponding to the index */ public static @NotNull String getZeroInitialisedData(int index, int startingLevel) throws IndexOutOfBoundsException { - switch(index) { - case USERNAME_INDEX: - return LEGACY_INVALID_OLD_USERNAME; //We'll keep using this value for legacy compatibility reasons (not sure if needed but don't care) - case 2: //Assumption: Used to be for something, no longer used - case 3: //Assumption: Used to be for something, no longer used - case 23: //Assumption: Used to be used for something, no longer used - case 33: //Assumption: Used to be used for something, no longer used - case LEGACY_LAST_LOGIN: - case HEALTHBAR: - return "IGNORED"; - case SKILLS_MINING: - case SKILLS_REPAIR: - case SKILLS_UNARMED: - case SKILLS_HERBALISM: - case SKILLS_EXCAVATION: - case SKILLS_ARCHERY: - case SKILLS_SWORDS: - case SKILLS_AXES: - case SKILLS_WOODCUTTING: - case SKILLS_ACROBATICS: - case SKILLS_TAMING: - case SKILLS_FISHING: - case SKILLS_ALCHEMY: - case SKILLS_CROSSBOWS: - case SKILLS_TRIDENTS: - return String.valueOf(startingLevel); - case OVERHAUL_LAST_LOGIN: - return String.valueOf(-1L); - case COOLDOWN_BERSERK: - case COOLDOWN_GIGA_DRILL_BREAKER: - case COOLDOWN_TREE_FELLER: - case COOLDOWN_GREEN_TERRA: - case COOLDOWN_SERRATED_STRIKES: - case COOLDOWN_SKULL_SPLITTER: - case COOLDOWN_SUPER_BREAKER: - case COOLDOWN_BLAST_MINING: - case COOLDOWN_SUPER_SHOTGUN: - case COOLDOWN_TRIDENTS: - case COOLDOWN_ARCHERY: - case SCOREBOARD_TIPS: - case COOLDOWN_CHIMAERA_WING: - case EXP_MINING: - case EXP_WOODCUTTING: - case EXP_REPAIR: - case EXP_UNARMED: - case EXP_HERBALISM: - case EXP_EXCAVATION: - case EXP_ARCHERY: - case EXP_SWORDS: - case EXP_AXES: - case EXP_ACROBATICS: - case EXP_TAMING: - case EXP_FISHING: - case EXP_ALCHEMY: - case EXP_CROSSBOWS: - case EXP_TRIDENTS: - return "0"; - case UUID_INDEX: - throw new IndexOutOfBoundsException(); //TODO: Add UUID recovery? Might not even be worth it. - } + //TODO: Add UUID recovery? Might not even be worth it. + return switch (index) { + case USERNAME_INDEX -> + LEGACY_INVALID_OLD_USERNAME; //We'll keep using this value for legacy compatibility reasons (not sure if needed but don't care) + //Assumption: Used to be for something, no longer used + //Assumption: Used to be for something, no longer used + //Assumption: Used to be used for something, no longer used + //Assumption: Used to be used for something, no longer used + case 2, 3, 23, 33, LEGACY_LAST_LOGIN, HEALTHBAR -> "IGNORED"; + case SKILLS_MINING, SKILLS_REPAIR, SKILLS_UNARMED, SKILLS_HERBALISM, SKILLS_EXCAVATION, SKILLS_ARCHERY, + SKILLS_SWORDS, SKILLS_AXES, SKILLS_WOODCUTTING, SKILLS_ACROBATICS, SKILLS_TAMING, SKILLS_FISHING, + SKILLS_ALCHEMY, SKILLS_CROSSBOWS, SKILLS_TRIDENTS, SKILLS_MACES -> String.valueOf(startingLevel); + case OVERHAUL_LAST_LOGIN -> String.valueOf(-1L); + case COOLDOWN_BERSERK, COOLDOWN_GIGA_DRILL_BREAKER, COOLDOWN_TREE_FELLER, COOLDOWN_GREEN_TERRA, + COOLDOWN_SERRATED_STRIKES, COOLDOWN_SKULL_SPLITTER, COOLDOWN_SUPER_BREAKER, COOLDOWN_BLAST_MINING, + COOLDOWN_SUPER_SHOTGUN, COOLDOWN_TRIDENTS, COOLDOWN_ARCHERY, COOLDOWN_MACES, SCOREBOARD_TIPS, COOLDOWN_CHIMAERA_WING, + EXP_MINING, EXP_WOODCUTTING, EXP_REPAIR, EXP_UNARMED, EXP_HERBALISM, EXP_EXCAVATION, EXP_ARCHERY, + EXP_SWORDS, EXP_AXES, EXP_ACROBATICS, EXP_TAMING, EXP_FISHING, EXP_ALCHEMY, EXP_CROSSBOWS, + EXP_TRIDENTS, EXP_MACES -> "0"; + case UUID_INDEX -> + throw new IndexOutOfBoundsException(); //TODO: Add UUID recovery? Might not even be worth it. + default -> throw new IndexOutOfBoundsException(); + }; - throw new IndexOutOfBoundsException(); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java b/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java index f19ec041e..32109deac 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java +++ b/src/main/java/com/gmail/nossr50/datatypes/LevelUpBroadcastPredicate.java @@ -25,56 +25,56 @@ public class LevelUpBroadcastPredicate implements Predi Player broadcastingPlayer = (Player) broadcaster; //Always a player no need to check cast //Broadcaster should be online - if(!broadcastingPlayer.isOnline()) { + if (!broadcastingPlayer.isOnline()) { return false; } McMMOPlayer mmoBroadcastingPlayer = UserManager.getPlayer(broadcastingPlayer); - if(mmoBroadcastingPlayer == null) { + if (mmoBroadcastingPlayer == null) { //This should never be null, but just in case... mcMMO.p.getLogger().severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); return false; } - if(t instanceof Player listeningPlayer) { + if (t instanceof Player listeningPlayer) { //Party Member Check - if(mcMMO.p.getGeneralConfig().isLevelUpBroadcastsPartyMembersOnly()) { + if (mcMMO.p.getGeneralConfig().isLevelUpBroadcastsPartyMembersOnly()) { McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer); - if(mmoListeningPlayer == null) { + if (mmoListeningPlayer == null) { return false; //No profile so therefor no party } Party playerWhoLeveledParty = mmoBroadcastingPlayer.getParty(); Party broadcastRecipientParty = mmoListeningPlayer.getParty(); - if(playerWhoLeveledParty == null || broadcastRecipientParty == null) { + if (playerWhoLeveledParty == null || broadcastRecipientParty == null) { return false; //No party on either player when being in the same party is required } - if(!playerWhoLeveledParty.equals(broadcastRecipientParty)) { + if (!playerWhoLeveledParty.equals(broadcastRecipientParty)) { return false; //Not in the same party when it is required } } //Same world check - if(isLevelUpBroadcastsSameWorldOnly()) { - if(!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { + if (isLevelUpBroadcastsSameWorldOnly()) { + if (!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { return false; //Not in the same world when its required } //Distance checks - if(mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastsRestrictDistance()) { - if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) { + if (mcMMO.p.getGeneralConfig().shouldLevelUpBroadcastsRestrictDistance()) { + if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getLevelUpBroadcastRadius())) { return false; } } } //Visibility checks - if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { + if (!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { return false; //Player who leveled should be invisible to this player so don't send the message } diff --git a/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java b/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java index 05e7a3a1a..1e6b278a8 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java +++ b/src/main/java/com/gmail/nossr50/datatypes/PowerLevelUpBroadcastPredicate.java @@ -25,56 +25,56 @@ public class PowerLevelUpBroadcastPredicate implements Player broadcastingPlayer = (Player) broadcaster; //Always a player no need to check cast //Broadcaster should be online - if(!broadcastingPlayer.isOnline()) { + if (!broadcastingPlayer.isOnline()) { return false; } McMMOPlayer mmoBroadcastingPlayer = UserManager.getPlayer(broadcastingPlayer); - if(mmoBroadcastingPlayer == null) { + if (mmoBroadcastingPlayer == null) { //This should never be null, but just in case... mcMMO.p.getLogger().severe("McMMOPlayer was null for broadcaster in LevelUpBroadcastPredicate when it should never be null!"); return false; } - if(t instanceof Player listeningPlayer) { + if (t instanceof Player listeningPlayer) { //Party Member Check - if(mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsPartyMembersOnly()) { + if (mcMMO.p.getGeneralConfig().isPowerLevelUpBroadcastsPartyMembersOnly()) { McMMOPlayer mmoListeningPlayer = UserManager.getPlayer(listeningPlayer); - if(mmoListeningPlayer == null) { + if (mmoListeningPlayer == null) { return false; //No profile so therefor no party } Party playerWhoLeveledParty = mmoBroadcastingPlayer.getParty(); Party broadcastRecipientParty = mmoListeningPlayer.getParty(); - if(playerWhoLeveledParty == null || broadcastRecipientParty == null) { + if (playerWhoLeveledParty == null || broadcastRecipientParty == null) { return false; //No party on either player when being in the same party is required } - if(!playerWhoLeveledParty.equals(broadcastRecipientParty)) { + if (!playerWhoLeveledParty.equals(broadcastRecipientParty)) { return false; //Not in the same party when it is required } } //Same world check - if(isPowerLevelUpBroadcastsSameWorldOnly()) { - if(!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { + if (isPowerLevelUpBroadcastsSameWorldOnly()) { + if (!mmoBroadcastingPlayer.getPlayer().getWorld().equals(listeningPlayer.getWorld())) { return false; //Not in the same world when its required } //Distance checks - if(mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastsRestrictDistance()) { - if(!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) { + if (mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcastsRestrictDistance()) { + if (!Misc.isNear(mmoBroadcastingPlayer.getPlayer().getLocation(), listeningPlayer.getLocation(), mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastRadius())) { return false; } } } //Visibility checks - if(!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { + if (!listeningPlayer.canSee(mmoBroadcastingPlayer.getPlayer()) && listeningPlayer != mmoBroadcastingPlayer.getPlayer()) { return false; //Player who leveled should be invisible to this player so don't send the message } diff --git a/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java b/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java index c8e089ab6..11a01cdec 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/database/DatabaseType.java @@ -14,8 +14,7 @@ public enum DatabaseType { if (typeName.equalsIgnoreCase("file")) { return FLATFILE; - } - else if (typeName.equalsIgnoreCase("mysql")) { + } else if (typeName.equalsIgnoreCase("mysql")) { return SQL; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java index 3ffb1cd94..2725daafe 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java +++ b/src/main/java/com/gmail/nossr50/datatypes/experience/SkillXpGain.java @@ -33,8 +33,7 @@ public class SkillXpGain implements Delayed { public int compareTo(SkillXpGain other) { if (this.expiryTime < other.expiryTime) { return -1; - } - else if (this.expiryTime > other.expiryTime) { + } else if (this.expiryTime > other.expiryTime) { return 1; } return 0; diff --git a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java index 4cac6d1e5..252644820 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOUrl.java @@ -8,10 +8,8 @@ public class McMMOUrl { public static final String urlSpigot = "https://spigot.mcmmo.org"; public static final String urlTranslate = "https://translate.mcmmo.org/"; - public static String getUrl(McMMOWebLinks webLinks) - { - switch(webLinks) - { + public static String getUrl(McMMOWebLinks webLinks) { + switch(webLinks) { case WIKI: return urlWiki; case PATREON: diff --git a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java index 9648883fb..2e7eb887b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java +++ b/src/main/java/com/gmail/nossr50/datatypes/json/McMMOWebLinks.java @@ -11,20 +11,16 @@ public enum McMMOWebLinks { HELP_TRANSLATE, WIKI; - public String getUrl() - { + public String getUrl() { return McMMOUrl.getUrl(this); } - public String getNiceTitle() - { + public String getNiceTitle() { return StringUtils.getCapitalized(toString()); } - public String getLocaleDescription() - { - switch (this) - { + public String getLocaleDescription() { + switch (this) { case WEBSITE: return LocaleLoader.getString( "JSON.URL.Website"); case DISCORD: diff --git a/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java b/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java index 137399009..9aac9b224 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java +++ b/src/main/java/com/gmail/nossr50/datatypes/meta/OldName.java @@ -8,8 +8,7 @@ import org.bukkit.metadata.FixedMetadataValue; */ public class OldName extends FixedMetadataValue { - public OldName(String oldName, mcMMO plugin) - { + public OldName(String oldName, mcMMO plugin) { super(plugin, oldName); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java index 270421f14..8089e025e 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ItemShareType.java @@ -15,17 +15,13 @@ public enum ItemShareType { public static ItemShareType getShareType(ItemStack itemStack) { if (ItemUtils.isMobDrop(itemStack)) { return LOOT; - } - else if (ItemUtils.isMiningDrop(itemStack)) { + } else if (ItemUtils.isMiningDrop(itemStack)) { return MINING; - } - else if (ItemUtils.isHerbalismDrop(itemStack)) { + } else if (ItemUtils.isHerbalismDrop(itemStack)) { return HERBALISM; - } - else if (ItemUtils.isWoodcuttingDrop(itemStack)) { + } else if (ItemUtils.isWoodcuttingDrop(itemStack)) { return WOODCUTTING; - } - else if (ItemUtils.isMiscDrop(itemStack)) { + } else if (ItemUtils.isMiscDrop(itemStack)) { return MISC; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java index 78ffb9966..d1983507b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/Party.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/Party.java @@ -85,13 +85,11 @@ public class Party { return onlineMembers; } - public List getVisibleMembers(Player player) - { + public List getVisibleMembers(Player player) { ArrayList visibleMembers = new ArrayList<>(); - for(Player p : onlineMembers) - { - if(player.canSee(p)) + for(Player p : onlineMembers) { + if (player.canSee(p)) visibleMembers.add(p); } @@ -347,7 +345,7 @@ public class Party { for(UUID playerUUID : members.keySet()) { OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerUUID); - if(offlinePlayer.isOnline() && player.canSee((Player) offlinePlayer)) { + if (offlinePlayer.isOnline() && player.canSee((Player) offlinePlayer)) { ChatColor onlineColor = leader.getUniqueId().equals(playerUUID) ? ChatColor.GOLD : ChatColor.GREEN; coloredNames.add(onlineColor + offlinePlayer.getName()); } else { @@ -361,7 +359,7 @@ public class Party { private void buildChatMessage(@NotNull StringBuilder stringBuilder, String @NotNull [] names) { for(int i = 0; i < names.length; i++) { - if(i + 1 >= names.length) { + if (i + 1 >= names.length) { stringBuilder .append(names[i]); } else { diff --git a/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java b/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java index 778ed08e6..3c136711b 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java +++ b/src/main/java/com/gmail/nossr50/datatypes/party/ShareMode.java @@ -14,8 +14,7 @@ public enum ShareMode { catch (IllegalArgumentException ex) { if (string.equalsIgnoreCase("even")) { return EQUAL; - } - else if (CommandUtils.shouldDisableToggle(string)) { + } else if (CommandUtils.shouldDisableToggle(string)) { return NONE; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java index ea9b09f15..464719ce0 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/McMMOPlayer.java @@ -32,6 +32,7 @@ import com.gmail.nossr50.skills.crossbows.CrossbowsManager; import com.gmail.nossr50.skills.excavation.ExcavationManager; import com.gmail.nossr50.skills.fishing.FishingManager; import com.gmail.nossr50.skills.herbalism.HerbalismManager; +import com.gmail.nossr50.skills.maces.MacesManager; import com.gmail.nossr50.skills.mining.MiningManager; import com.gmail.nossr50.skills.repair.RepairManager; import com.gmail.nossr50.skills.salvage.SalvageManager; @@ -71,6 +72,9 @@ import java.util.EnumMap; import java.util.Map; import java.util.UUID; +import static com.gmail.nossr50.util.EventUtils.callPlayerAbilityActivateEvent; +import static java.util.Objects.requireNonNull; + public class McMMOPlayer implements Identified { private final @NotNull Identity identity; @@ -119,6 +123,8 @@ public class McMMOPlayer implements Identified { private PrimarySkillType lastSkillShownScoreboard = PrimarySkillType.values()[0]; public McMMOPlayer(Player player, PlayerProfile profile) { + requireNonNull(player, "player cannot be null"); + requireNonNull(profile, "profile cannot be null"); this.playerName = player.getName(); UUID uuid = player.getUniqueId(); identity = Identity.identity(uuid); @@ -151,7 +157,7 @@ public class McMMOPlayer implements Identified { this.chatChannel = ChatChannel.NONE; - if(ChatConfig.getInstance().isSpyingAutomatic() && Permissions.adminChatSpy(getPlayer())) { + if (ChatConfig.getInstance().isSpyingAutomatic() && Permissions.adminChatSpy(getPlayer())) { chatSpy = true; } } @@ -220,6 +226,9 @@ public class McMMOPlayer implements Identified { case WOODCUTTING: skillManagers.put(primarySkillType, new WoodcuttingManager(this)); break; + case MACES: + skillManagers.put(primarySkillType, new MacesManager(this)); + break; default: throw new InvalidSkillException("The skill named has no manager! Contact the devs!"); } @@ -241,42 +250,38 @@ public class McMMOPlayer implements Identified { this.lastSkillShownScoreboard = primarySkillType; } - public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) - { + public void processPostXpEvent(PrimarySkillType primarySkillType, Plugin plugin, XPGainSource xpGainSource) { //Check if they've reached the power level cap just now - if(hasReachedPowerLevelCap()) { + if (hasReachedPowerLevelCap()) { NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.PowerLevel", String.valueOf(mcMMO.p.getGeneralConfig().getPowerLevelCap())); - } else if(hasReachedLevelCap(primarySkillType)) { + } else if (hasReachedLevelCap(primarySkillType)) { NotificationManager.sendPlayerInformationChatOnly(player, "LevelCap.Skill", String.valueOf(mcMMO.p.getSkillTools().getLevelCap(primarySkillType)), mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType)); } //Updates from Party sources - if(xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled()) + if (xpGainSource == XPGainSource.PARTY_MEMBERS && !ExperienceConfig.getInstance().isPartyExperienceBarsEnabled()) return; //Updates from passive sources (Alchemy, Smelting, etc...) - if(xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) + if (xpGainSource == XPGainSource.PASSIVE && !ExperienceConfig.getInstance().isPassiveGainsExperienceBarsEnabled()) return; updateXPBar(primarySkillType, plugin); } - public void processUnlockNotifications(mcMMO plugin, PrimarySkillType primarySkillType, int skillLevel) - { + public void processUnlockNotifications(mcMMO plugin, PrimarySkillType primarySkillType, int skillLevel) { RankUtils.executeSkillUnlockNotifications(plugin, this, primarySkillType, skillLevel); } - public void updateXPBar(PrimarySkillType primarySkillType, Plugin plugin) - { + public void updateXPBar(PrimarySkillType primarySkillType, Plugin plugin) { //XP BAR UPDATES experienceBarManager.updateExperienceBar(primarySkillType, plugin); } - public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) - { - if(SkillTools.isChildSkill(primarySkillType)) { + public double getProgressInCurrentSkillLevel(PrimarySkillType primarySkillType) { + if (SkillTools.isChildSkill(primarySkillType)) { return 1.0D; } @@ -313,6 +318,10 @@ public class McMMOPlayer implements Identified { return (TridentsManager) skillManagers.get(PrimarySkillType.TRIDENTS); } + public MacesManager getMacesManager() { + return (MacesManager) skillManagers.get(PrimarySkillType.MACES); + } + public ExcavationManager getExcavationManager() { return (ExcavationManager) skillManagers.get(PrimarySkillType.EXCAVATION); } @@ -589,7 +598,7 @@ public class McMMOPlayer implements Identified { * @return */ public boolean hasReachedLevelCap(PrimarySkillType primarySkillType) { - if(hasReachedPowerLevelCap()) + if (hasReachedPowerLevelCap()) return true; return getSkillLevel(primarySkillType) >= mcMMO.p.getSkillTools().getLevelCap(primarySkillType); @@ -611,7 +620,7 @@ public class McMMOPlayer implements Identified { * @param xp Experience amount to process */ public void beginXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if(xp <= 0) { + if (xp <= 0) { return; } @@ -643,7 +652,7 @@ public class McMMOPlayer implements Identified { * @param xp Experience amount to process */ public void beginUnsharedXpGain(PrimarySkillType skill, float xp, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if(player.getGameMode() == GameMode.CREATIVE) + if (player.getGameMode() == GameMode.CREATIVE) return; applyXpGain(skill, modifyXpGain(skill, xp), xpGainReason, xpGainSource); @@ -696,7 +705,7 @@ public class McMMOPlayer implements Identified { * @param primarySkillType The skill to check */ private void checkXp(PrimarySkillType primarySkillType, XPGainReason xpGainReason, XPGainSource xpGainSource) { - if(hasReachedLevelCap(primarySkillType)) + if (hasReachedLevelCap(primarySkillType)) return; if (getSkillXpLevelRaw(primarySkillType) < getXpToLevel(primarySkillType)) { @@ -739,11 +748,11 @@ public class McMMOPlayer implements Identified { * Players & Profiles */ - public Player getPlayer() { + public @NotNull Player getPlayer() { return player; } - public PlayerProfile getProfile() { + public @NotNull PlayerProfile getProfile() { return profile; } @@ -893,8 +902,7 @@ public class McMMOPlayer implements Identified { //TODO: This is hacky and temporary solution until skills are move to the new system //Potential problems with this include skills with two super abilities (ie mining) - if(!RankUtils.hasUnlockedSubskill(player, subSkillType)) - { + if (!RankUtils.hasUnlockedSubskill(player, subSkillType)) { int diff = RankUtils.getSuperAbilityUnlockRequirement(superAbilityType) - getSkillLevel(primarySkillType); //Inform the player they are not yet skilled enough @@ -917,7 +925,7 @@ public class McMMOPlayer implements Identified { return; } - if (EventUtils.callPlayerAbilityActivateEvent(player, primarySkillType).isCancelled()) { + if (callPlayerAbilityActivateEvent(this, primarySkillType).isCancelled()) { return; } @@ -928,8 +936,7 @@ public class McMMOPlayer implements Identified { int ticks; //Ability cap of 0 or below means no cap - if(abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, 2 + (Math.min(abilityLengthCap, getSkillLevel(primarySkillType)) / abilityLengthVar), superAbilityType.getMaxLength()); } else { ticks = PerksUtils.handleActivationPerks(player, 2 + (getSkillLevel(primarySkillType) / abilityLengthVar), superAbilityType.getMaxLength()); @@ -1011,7 +1018,7 @@ public class McMMOPlayer implements Identified { * IF THE TOOL IS AN AXE * */ - if(tool == ToolType.AXE) { + if (tool == ToolType.AXE) { processAxeToolMessages(); } else { NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, tool.getRaiseTool()); @@ -1032,20 +1039,20 @@ public class McMMOPlayer implements Identified { /* * IF BOTH TREE FELLER & SKULL SPLITTER ARE ON CD */ - if(isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { + if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { tooTiredMultiple(PrimarySkillType.WOODCUTTING, SubSkillType.WOODCUTTING_TREE_FELLER, SuperAbilityType.TREE_FELLER, SubSkillType.AXES_SKULL_SPLITTER, SuperAbilityType.SKULL_SPLITTER); /* * IF TREE FELLER IS ON CD * AND PLAYER IS LOOKING AT TREE */ - } else if(isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) + } else if (isAbilityOnCooldown(SuperAbilityType.TREE_FELLER) && BlockUtils.isPartOfTree(rayCast)) { raiseToolWithCooldowns(SubSkillType.WOODCUTTING_TREE_FELLER, SuperAbilityType.TREE_FELLER); /* * IF SKULL SPLITTER IS ON CD */ - } else if(isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { + } else if (isAbilityOnCooldown(SuperAbilityType.SKULL_SPLITTER)) { raiseToolWithCooldowns(SubSkillType.AXES_SKULL_SPLITTER, SuperAbilityType.SKULL_SPLITTER); } else { NotificationManager.sendPlayerInformation(player, NotificationType.TOOL, ToolType.AXE.getRaiseTool()); @@ -1143,7 +1150,7 @@ public class McMMOPlayer implements Identified { */ public void logout(boolean syncSave) { Player thisPlayer = getPlayer(); - if(getPlayer().hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (getPlayer().hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { RuptureTaskMeta ruptureTaskMeta = (RuptureTaskMeta) getPlayer().getMetadata(MetadataConstants.METADATA_KEY_RUPTURE).get(0); //Punish a logout @@ -1162,7 +1169,7 @@ public class McMMOPlayer implements Identified { UserManager.remove(thisPlayer); - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.teardownPlayer(thisPlayer); if (inParty()) { diff --git a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java index 71abb6418..80f94427d 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java +++ b/src/main/java/com/gmail/nossr50/datatypes/player/PlayerProfile.java @@ -100,7 +100,7 @@ public class PlayerProfile { loaded = true; - if(lastLogin != null) + if (lastLogin != null) this.lastLogin = lastLogin; } @@ -130,17 +130,16 @@ public class PlayerProfile { if (changed) { mcMMO.p.getLogger().severe("PlayerProfile saving failed for player: " + playerName + " " + uuid); - if(saveAttempts > 0) { + if (saveAttempts > 0) { mcMMO.p.getLogger().severe("Attempted to save profile for player "+getPlayerName() + " resulted in failure. "+saveAttempts+" have been made so far."); } - if(saveAttempts < 10) - { + if (saveAttempts < 10) { saveAttempts++; //Back out of async saving if we detect a server shutdown, this is not always going to be caught - if(mcMMO.isServerShutdownExecuted() || useSync) + if (mcMMO.isServerShutdownExecuted() || useSync) mcMMO.p.getFoliaLib().getImpl().runNextTick(new PlayerProfileSaveTask(this, true)); else scheduleAsyncSave(); @@ -271,7 +270,7 @@ public class PlayerProfile { } public int getSkillXpLevel(PrimarySkillType skill) { - if(SkillTools.isChildSkill(skill)) { + if (SkillTools.isChildSkill(skill)) { return 0; } @@ -339,7 +338,7 @@ public class PlayerProfile { markProfileDirty(); //Don't allow levels to be negative - if(level < 0) + if (level < 0) level = 0; skills.put(skill, level); @@ -372,8 +371,7 @@ public class PlayerProfile { for (PrimarySkillType parentSkill : parentSkills) { skillsXp.put(parentSkill, skillsXp.get(parentSkill) + dividedXP); } - } - else { + } else { skillsXp.put(skill, skillsXp.get(skill) + xp); } } @@ -424,7 +422,7 @@ public class PlayerProfile { * @return the total amount of Xp until next level */ public int getXpToLevel(PrimarySkillType primarySkillType) { - if(SkillTools.isChildSkill(primarySkillType)) { + if (SkillTools.isChildSkill(primarySkillType)) { return 0; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java index 26e0f17d9..85952bac7 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/MaterialType.java @@ -37,7 +37,7 @@ public enum MaterialType { return Material.DIAMOND; case NETHERITE: - if(Material.getMaterial("NETHERITE_SCRAP") != null) + if (Material.getMaterial("NETHERITE_SCRAP") != null) return Material.getMaterial("NETHERITE_SCRAP"); else return Material.DIAMOND; diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java index df951d783..e6f0da0c5 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/ModConfigType.java @@ -9,11 +9,9 @@ public enum ModConfigType { public static ModConfigType getModConfigType(String materialName) { if (materialName.contains("HELM") || (materialName.contains("CHEST") && !materialName.contains("CHESTNUT")) || materialName.contains("LEGS") || materialName.contains("LEGGINGS") || materialName.contains("BOOT")) { return ARMOR; - } - else if (materialName.contains("PICKAXE") || materialName.contains("AXE") || (materialName.contains("BOW") && !materialName.contains("BOWL")) || materialName.contains("HOE") || materialName.contains("SHOVEL") || materialName.contains("SWORD")) { + } else if (materialName.contains("PICKAXE") || materialName.contains("AXE") || (materialName.contains("BOW") && !materialName.contains("BOWL")) || materialName.contains("HOE") || materialName.contains("SHOVEL") || materialName.contains("SWORD")) { return TOOLS; - } - else if (materialName.contains("LOG") || materialName.contains("LEAVES") || materialName.contains("FLOWER") || materialName.contains("PLANT") || materialName.contains("CROP") || materialName.contains("ORE") || materialName.contains("DIRT") || materialName.contains("SAND") || materialName.contains("GRASS")) { + } else if (materialName.contains("LOG") || materialName.contains("LEAVES") || materialName.contains("FLOWER") || materialName.contains("PLANT") || materialName.contains("CROP") || materialName.contains("ORE") || materialName.contains("DIRT") || materialName.contains("SAND") || materialName.contains("GRASS")) { return BLOCKS; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java index 9dfecd55b..31f315c1f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/PrimarySkillType.java @@ -20,6 +20,7 @@ public enum PrimarySkillType { EXCAVATION, FISHING, HERBALISM, + MACES, MINING, REPAIR, SALVAGE, diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java index 48910bb77..53e84ec5d 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SubSkillType.java @@ -57,6 +57,9 @@ public enum SubSkillType { HERBALISM_HYLIAN_LUCK, HERBALISM_SHROOM_THUMB, + /* Maces */ + MACES_MACES_LIMIT_BREAK(10), + /* Mining */ MINING_BIGGER_BOMBS(1), MINING_BLAST_MINING(8), @@ -125,18 +128,15 @@ public enum SubSkillType { * If our SubSkillType has more than 1 rank define it * @param numRanks The number of ranks our SubSkillType has */ - SubSkillType(int numRanks) - { + SubSkillType(int numRanks) { this.numRanks = numRanks; } - SubSkillType() - { + SubSkillType() { this.numRanks = 0; } - public int getNumRanks() - { + public int getNumRanks() { return numRanks; } @@ -167,8 +167,7 @@ public enum SubSkillType { * Get the string representation of the permission node for this subskill * @return the permission node for this subskill */ - public String getPermissionNodeAddress() - { + public String getPermissionNodeAddress() { //TODO: This could be optimized return "mcmmo.ability." + getParentSkill().toString().toLowerCase(Locale.ENGLISH) + "." + getConfigName(toString()).toLowerCase(Locale.ENGLISH); } @@ -198,12 +197,10 @@ public enum SubSkillType { * Split the string up so we can capitalize each part */ String subskillNameWithoutPrefix = subSkillName.substring(subStringIndex); - if(subskillNameWithoutPrefix.contains("_")) - { + if (subskillNameWithoutPrefix.contains("_")) { String[] splitStrings = subskillNameWithoutPrefix.split("_"); - for(String string : splitStrings) - { + for(String string : splitStrings) { endResult.append(StringUtils.getCapitalized(string)); } } else { @@ -225,8 +222,7 @@ public enum SubSkillType { * Returns the name of the parent skill from the Locale file * @return The parent skill as defined in the locale */ - public String getParentNiceNameLocale() - { + public String getParentNiceNameLocale() { return LocaleLoader.getString(StringUtils.getCapitalized(getParentSkill().toString())+".SkillName"); } @@ -235,8 +231,7 @@ public enum SubSkillType { * @param subSkillType target subskill * @return the "nice" name without spaces */ - public String getNiceNameNoSpaces(SubSkillType subSkillType) - { + public String getNiceNameNoSpaces(SubSkillType subSkillType) { return getConfigName(subSkillType.toString()); } @@ -260,18 +255,15 @@ public enum SubSkillType { return subStringIndex; } - public String getLocaleKeyRoot() - { + public String getLocaleKeyRoot() { return StringUtils.getCapitalized(getParentSkill().toString())+".SubSkill."+getConfigName(toString()); } - public String getLocaleName() - { + public String getLocaleName() { return getFromLocaleSubAddress(".Name"); } - public String getLocaleDescription() - { + public String getLocaleDescription() { return getFromLocaleSubAddress(".Description"); } @@ -281,13 +273,11 @@ public enum SubSkillType { public String getLocaleStatExtraDescription() { return getFromLocaleSubAddress(".Stat.Extra"); } public String getLocaleKeyStatExtraDescription() { return getLocaleKeyFromSubAddress(".Stat.Extra"); } - public String getLocaleStat(String... vars) - { + public String getLocaleStat(String... vars) { return LocaleLoader.getString("Ability.Generic.Template", (Object[]) vars); } - public String getCustomLocaleStat(String... vars) - { + public String getCustomLocaleStat(String... vars) { return LocaleLoader.getString("Ability.Generic.Template.Custom", (Object[]) vars); } @@ -295,8 +285,7 @@ public enum SubSkillType { return LocaleLoader.getString(getLocaleKeyRoot() + s); } - private String getLocaleKeyFromSubAddress(String s) - { + private String getLocaleKeyFromSubAddress(String s) { return getLocaleKeyRoot() + s; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java index f876ce53e..3fcf2992c 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/SuperAbilityType.java @@ -72,19 +72,26 @@ public enum SuperAbilityType { "Swords.Skills.SS.Other.Off", "Swords.SubSkill.SerratedStrikes.Name"), SUPER_SHOTGUN( - null, - null, - "Crossbows.Skills.SSG.Other.On", - "Crossbows.Skills.SSG.Refresh", - null, - "Crossbows.SubSkill.SuperShotgun.Name"), + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder"), TRIDENTS_SUPER_ABILITY( - "Tridents.Skills.TA.On", - "Tridents.Skills.TA.Off", - "Tridents.Skills.TA.Other.On", - "Tridents.Skills.TA.Refresh", - "Tridents.Skills.TA.Other.Off", - "Tridents.SubSkill.TridentAbility.Name"), + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder"), + MACES_SUPER_ABILITY( + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder", + "Placeholder"), /** * Has cooldown - but has to share a skill with Super Breaker, so needs special treatment @@ -199,16 +206,15 @@ public enum SuperAbilityType { public boolean getPermissions(Player player) { return switch (this) { case BERSERK -> Permissions.berserk(player); - case EXPLOSIVE_SHOT -> Permissions.explosiveShot(player); case BLAST_MINING -> Permissions.remoteDetonation(player); case GIGA_DRILL_BREAKER -> Permissions.gigaDrillBreaker(player); case GREEN_TERRA -> Permissions.greenTerra(player); case SERRATED_STRIKES -> Permissions.serratedStrikes(player); case SKULL_SPLITTER -> Permissions.skullSplitter(player); case SUPER_BREAKER -> Permissions.superBreaker(player); - case SUPER_SHOTGUN -> Permissions.superShotgun(player); case TREE_FELLER -> Permissions.treeFeller(player); - case TRIDENTS_SUPER_ABILITY -> Permissions.tridentsSuper(player); + // TODO: once implemented, return permissions for the following abilities + case EXPLOSIVE_SHOT, TRIDENTS_SUPER_ABILITY, SUPER_SHOTGUN, MACES_SUPER_ABILITY -> false; }; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java b/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java index dd61867d5..69422c1a2 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/ToolType.java @@ -13,7 +13,8 @@ public enum ToolType { SWORD("Swords.Ability.Lower", "Swords.Ability.Ready"), CROSSBOW("Crossbows.Ability.Lower", "Crossbows.Ability.Ready"), BOW("Archery.Ability.Lower", "Archery.Ability.Ready"), - TRIDENTS("Tridents.Ability.Lower", "Tridents.Ability.Ready"); + TRIDENTS("Tridents.Ability.Lower", "Tridents.Ability.Ready"), + MACES("Maces.Ability.Lower", "Maces.Ability.Ready"); private final String lowerTool; private final String raiseTool; @@ -45,6 +46,8 @@ public enum ToolType { return ItemUtils.isCrossbow(itemStack); case TRIDENTS: return ItemUtils.isTrident(itemStack); + case MACES: + return ItemUtils.isMace(itemStack); case FISTS: return itemStack.getType() == Material.AIR; diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java index c767004df..0b0654dda 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/AlchemyPotion.java @@ -1,167 +1,149 @@ package com.gmail.nossr50.datatypes.skills.alchemy; -import com.gmail.nossr50.config.skills.alchemy.PotionConfig; -import org.bukkit.Color; +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.PotionUtil; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.Potion; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; -import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; + +import static com.gmail.nossr50.util.PotionUtil.samePotionType; +import static java.util.Objects.requireNonNull; public class AlchemyPotion { - private final Material material; - private PotionData data; - private String name; - private List lore; - private List effects; - private Color color; - private Map children; + private final @NotNull String potionConfigName; + private final @NotNull ItemStack potionItemStack; + private final @NotNull Map alchemyPotionChildren; - public AlchemyPotion(Material material, PotionData data, String name, List lore, List effects, Color color, Map children) { - this.material = material; - this.data = data; - this.lore = lore; - this.name = name; - this.effects = effects; - this.children = children; - this.color = color; + public AlchemyPotion(@NotNull String potionConfigName, @NotNull ItemStack potionItemStack, + @NotNull Map alchemyPotionChildren) { + this.potionConfigName = requireNonNull(potionConfigName, "potionConfigName cannot be null"); + this.potionItemStack = requireNonNull(potionItemStack, "potionItemStack cannot be null"); + this.alchemyPotionChildren = requireNonNull(alchemyPotionChildren, "alchemyPotionChildren cannot be null"); } - public String toString() { - return "AlchemyPotion{" + data + ", " + name + ", Effects[" + effects.size() + "], Children[" + children.size() + "]}"; + public @NotNull ItemStack toItemStack(int amount) { + final ItemStack clone = potionItemStack.clone(); + clone.setAmount(Math.max(1, amount)); + return clone; } - public ItemStack toItemStack(int amount) { - ItemStack potion = new ItemStack(material, amount); - PotionMeta meta = (PotionMeta) potion.getItemMeta(); - - meta.setBasePotionData(data); - if (this.getName() != null) { - meta.setDisplayName(this.getName()); - } - - if (this.getLore() != null && !this.getLore().isEmpty()) { - meta.setLore(this.getLore()); - } - - if (!this.getEffects().isEmpty()) { - for (PotionEffect effect : this.getEffects()) { - meta.addCustomEffect(effect, true); - } - } - - if (this.getColor() != null) { - meta.setColor(this.getColor()); - } - - potion.setItemMeta(meta); - return potion; + public @NotNull Map getAlchemyPotionChildren() { + return alchemyPotionChildren; } - public Material getMaterial() { - return material; - } - - public Potion toPotion(int amount) { - return Potion.fromItemStack(this.toItemStack(amount)); - } - - public PotionData getData() { - return data; - } - - public void setData(PotionData data) { - this.data = data; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getLore() { - return lore; - } - - public void setLore(List lore) { - this.lore = lore; - } - - public List getEffects() { - return effects; - } - - public void setEffects(List effects) { - this.effects = effects; - } - - public Color getColor() { - return color; - } - - public void setColor(Color color) { - this.color = color; - } - - public Map getChildren() { - return children; - } - - public void setChildren(Map children) { - this.children = children; - } - - public AlchemyPotion getChild(ItemStack ingredient) { - if (!children.isEmpty()) { - for (Entry child : children.entrySet()) { + public @Nullable AlchemyPotion getChild(@NotNull ItemStack ingredient) { + if (!alchemyPotionChildren.isEmpty()) { + for (Entry child : alchemyPotionChildren.entrySet()) { if (ingredient.isSimilar(child.getKey())) { - return PotionConfig.getInstance().getPotion(child.getValue()); + return mcMMO.p.getPotionConfig().getPotion(child.getValue()); } } } return null; } - public boolean isSimilar(ItemStack item) { - if (item.getType() != material) { + public boolean isSimilarPotion(@NotNull ItemStack otherPotion) { + requireNonNull(otherPotion, "otherPotion cannot be null"); + if (otherPotion.getType() != potionItemStack.getType()) { return false; } - if (!item.hasItemMeta()) { + + // no potion meta, no match + if (!otherPotion.hasItemMeta()) { return false; } - PotionMeta meta = (PotionMeta) item.getItemMeta(); - PotionData that = meta.getBasePotionData(); - if (data.getType() != that.getType()) { + + /* + * Compare custom effects on both potions. + */ + + final PotionMeta otherPotionMeta = (PotionMeta) otherPotion.getItemMeta(); + // compare custom effects on both potions, this has to be done in two traversals + // comparing thisPotionMeta -> otherPotionMeta and otherPotionMeta -> thisPotionMeta + if (hasDifferingCustomEffects(getAlchemyPotionMeta(), otherPotionMeta) + || hasDifferingCustomEffects(otherPotionMeta, getAlchemyPotionMeta())) { return false; } - if (data.isExtended() != that.isExtended()) { + + if (!samePotionType(getAlchemyPotionMeta(), otherPotionMeta)) { return false; } - if (data.isUpgraded() != that.isUpgraded()) { + + // Legacy only comparison, compare PotionData + if (!PotionUtil.isPotionDataEqual(getAlchemyPotionMeta(), otherPotionMeta)) { return false; } - for (PotionEffect effect : effects) { - if (!meta.hasCustomEffect(effect.getType())) { - return false; + + /* + * If one potion has lore and the other does not, then they are not the same potion. + * If both have lore, compare the lore. + * If neither have lore, they may be the same potion. + */ + if (!otherPotionMeta.hasLore() && getAlchemyPotionMeta().hasLore() + || !getAlchemyPotionMeta().hasLore() && otherPotionMeta.hasLore()) { + return false; + } + + return !otherPotionMeta.hasLore() || !getAlchemyPotionMeta().hasLore() + || otherPotionMeta.getLore().equals(getAlchemyPotionMeta().getLore()); + } + + private boolean hasDifferingCustomEffects(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + for (int i = 0; i < potionMeta.getCustomEffects().size(); i++) { + var effect = potionMeta.getCustomEffects().get(i); + + // One has an effect the other does not, they are not the same potion + if (!otherPotionMeta.hasCustomEffect(effect.getType())) { + return true; + } + + var otherEffect = otherPotionMeta.getCustomEffects().get(i); + // Amplifier or duration are not equal, they are not the same potion + if (effect.getAmplifier() != otherEffect.getAmplifier() + || effect.getDuration() != otherEffect.getDuration()) { + return true; } } - if (!meta.hasLore() && !lore.isEmpty()) { - return false; - } - if (!(lore.isEmpty() && !meta.hasLore()) && !meta.getLore().equals(lore)) { - return false; - } - if (!meta.hasDisplayName() && name != null) { - return false; - } - return (name == null && !meta.hasDisplayName()) || meta.getDisplayName().equals(name); + return false; + } + + public PotionMeta getAlchemyPotionMeta() { + return (PotionMeta) potionItemStack.getItemMeta(); + } + + public boolean isSplash() { + return potionItemStack.getType() == Material.SPLASH_POTION; + } + + public boolean isLingering() { + return potionItemStack.getType() == Material.LINGERING_POTION; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AlchemyPotion that = (AlchemyPotion) o; + return Objects.equals(potionConfigName, that.potionConfigName) && Objects.equals(potionItemStack, that.potionItemStack) && Objects.equals(alchemyPotionChildren, that.alchemyPotionChildren); + } + + @Override + public int hashCode() { + return Objects.hash(potionConfigName, potionItemStack, alchemyPotionChildren); + } + + @Override + public String toString() { + return "AlchemyPotion{" + + "potionConfigName='" + potionConfigName + '\'' + + ", potionItemStack=" + potionItemStack + + ", alchemyPotionChildren=" + alchemyPotionChildren + + '}'; } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java index fe2778eed..7825c717f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/alchemy/PotionStage.java @@ -1,11 +1,10 @@ package com.gmail.nossr50.datatypes.skills.alchemy; -import org.bukkit.Material; -import org.bukkit.potion.PotionData; +import com.gmail.nossr50.util.PotionUtil; +import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionType; -import java.util.List; +import static com.gmail.nossr50.util.PotionUtil.*; public enum PotionStage { FIVE(5), @@ -35,36 +34,37 @@ public enum PotionStage { } public static PotionStage getPotionStage(AlchemyPotion input, AlchemyPotion output) { - PotionStage potionStage = getPotionStage(output); - if (!isWaterBottle(input) && getPotionStage(input) == potionStage) { - potionStage = PotionStage.FIVE; + PotionStage outputPotionStage = getPotionStage(output); + PotionStage inputPotionStage = getPotionStage(input); + if (!isWaterBottle(input) && inputPotionStage == outputPotionStage) { + outputPotionStage = PotionStage.FIVE; } - return potionStage; + return outputPotionStage; } - private static boolean isWaterBottle(AlchemyPotion input) { - return input.getData().getType() == PotionType.WATER; + private static boolean isWaterBottle(AlchemyPotion alchemyPotion) { + return isPotionTypeWater(alchemyPotion.getAlchemyPotionMeta()); } public static PotionStage getPotionStage(AlchemyPotion alchemyPotion) { - PotionData data = alchemyPotion.getData(); - List effects = alchemyPotion.getEffects(); + final PotionMeta potionMeta = alchemyPotion.getAlchemyPotionMeta(); int stage = 1; // Check if potion has an effect of any sort - if (data.getType().getEffectType() != null || !effects.isEmpty()) { + if (!potionMeta.getCustomEffects().isEmpty() + || PotionUtil.hasBasePotionEffects(potionMeta)) { stage++; } // Check if potion has a glowstone dust amplifier // Else check if the potion has a custom effect with an amplifier added by mcMMO - if (data.isUpgraded()) { + if (isStrong(potionMeta)) { stage++; - } else if(!effects.isEmpty()) { - for (PotionEffect effect : effects){ - if(effect.getAmplifier() > 0){ + } else if (!potionMeta.getCustomEffects().isEmpty()) { + for (PotionEffect effect : potionMeta.getCustomEffects()){ + if (effect.getAmplifier() > 0){ stage++; break; } @@ -72,12 +72,12 @@ public enum PotionStage { } // Check if potion has a redstone dust amplifier - if (data.isExtended()) { + if (isLong(potionMeta)) { stage++; } // Check if potion has a gunpowder amplifier - if (alchemyPotion.getMaterial() == Material.SPLASH_POTION || alchemyPotion.getMaterial() == Material.LINGERING_POTION) { + if (alchemyPotion.isSplash() || alchemyPotion.isLingering()) { stage++; } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java index 109ece783..7a933f010 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/AbstractSubSkill.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.datatypes.skills.subskills; import com.gmail.nossr50.config.CoreSkillsConfig; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.interfaces.Interaction; import com.gmail.nossr50.datatypes.skills.subskills.interfaces.Rank; @@ -17,8 +18,7 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S protected String configKeyPrimary; protected SubSkillType subSkillType; - public AbstractSubSkill(String configKeySubSkill, String configKeyPrimary, SubSkillType subSkillType) - { + public AbstractSubSkill(String configKeySubSkill, String configKeyPrimary, SubSkillType subSkillType) { this.configKeySubSkill = configKeySubSkill; this.configKeyPrimary = configKeyPrimary; this.subSkillType = subSkillType; @@ -48,13 +48,13 @@ public abstract class AbstractSubSkill implements SubSkill, Interaction, Rank, S /** * Prints detailed info about this subskill to the player * - * @param player the target player + * @param mmoPlayer the target player */ @Override - public void printInfo(Player player) { + public void printInfo(McMMOPlayer mmoPlayer) { /* DEFAULT SETTINGS PRINT THE BARE MINIMUM */ - //TextComponentFactory.sendPlayerUrlHeader(player); + final Player player = mmoPlayer.getPlayer(); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Header")); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.SubSkillHeader", getConfigKeyName())); player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.DetailsHeader")); diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java index 15ea49679..3c2bc1d66 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/acrobatics/Roll.java @@ -4,7 +4,6 @@ import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.interactions.NotificationType; import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.locale.LocaleLoader; @@ -13,7 +12,6 @@ import com.gmail.nossr50.util.EventUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; -import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.PerksUtils; @@ -26,7 +24,6 @@ import net.kyori.adventure.text.TextComponent; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SoundCategory; -import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventPriority; @@ -64,29 +61,29 @@ public class Roll extends AcrobaticsSubSkill { EntityDamageEvent entityDamageEvent = (EntityDamageEvent) event; //Make sure a real player was damaged in this event - if(!EventUtils.isRealPlayerDamaged(entityDamageEvent)) + if (!EventUtils.isRealPlayerDamaged(entityDamageEvent)) return false; if (entityDamageEvent.getCause() == EntityDamageEvent.DamageCause.FALL) {//Grab the player - McMMOPlayer mcMMOPlayer = EventUtils.getMcMMOPlayer(entityDamageEvent.getEntity()); + McMMOPlayer mmoPlayer = EventUtils.getMcMMOPlayer(entityDamageEvent.getEntity()); - if (mcMMOPlayer == null) + if (mmoPlayer == null) return false; /* * Check for success */ - Player player = (Player) ((EntityDamageEvent) event).getEntity(); - if (canRoll(player)) { - entityDamageEvent.setDamage(rollCheck(player, mcMMOPlayer, entityDamageEvent.getFinalDamage())); + + if (canRoll(mmoPlayer)) { + entityDamageEvent.setDamage(rollCheck(mmoPlayer, entityDamageEvent.getFinalDamage())); if (entityDamageEvent.getFinalDamage() == 0) { entityDamageEvent.setCancelled(true); return true; } - } else if(mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.ACROBATICS)) { + } else if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(mmoPlayer.getPlayer(), PrimarySkillType.ACROBATICS)) { //Give XP Anyways - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, ((EntityDamageEvent) event).getFinalDamage(), false), XPGainReason.PVE); } } @@ -118,26 +115,25 @@ public class Roll extends AcrobaticsSubSkill { * Adds detailed stats specific to this skill * * @param componentBuilder target component builder - * @param player target player + * @param mmoPlayer target player */ @Override - public void addStats(TextComponent.Builder componentBuilder, Player player) { + public void addStats(TextComponent.Builder componentBuilder, McMMOPlayer mmoPlayer) { String rollChance, rollChanceLucky, gracefulRollChance, gracefulRollChanceLucky; /* Values related to the player */ - PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); - float skillValue = playerProfile.getSkillLevel(getPrimarySkill()); - boolean isLucky = Permissions.lucky(player, getPrimarySkill()); + float skillValue = mmoPlayer.getSkillLevel(getPrimarySkill()); + boolean isLucky = Permissions.lucky(mmoPlayer.getPlayer(), getPrimarySkill()); - String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(player, SubSkillType.ACROBATICS_ROLL); + String[] rollStrings = ProbabilityUtil.getRNGDisplayValues(mmoPlayer, SubSkillType.ACROBATICS_ROLL); rollChance = rollStrings[0]; rollChanceLucky = rollStrings[1]; /* * Graceful is double the odds of a normal roll */ - Probability probability = getRollProbability(player); - Probability gracefulProbability = Probability.ofPercent(probability.getValue() * 2); + Probability probability = getRollProbability(mmoPlayer); + Probability gracefulProbability = Probability.ofValue(probability.getValue() * 2); String[] gracefulRollStrings = ProbabilityUtil.getRNGDisplayValues(gracefulProbability); gracefulRollChance = gracefulRollStrings[0]; gracefulRollChanceLucky = gracefulRollStrings[1]; @@ -160,8 +156,7 @@ public class Roll extends AcrobaticsSubSkill { //Advanced //Lucky Notice - if(isLucky) - { + if (isLucky) { componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Header"))); componentBuilder.append(Component.newline()); componentBuilder.append(Component.text(LocaleLoader.getString("JSON.JWrapper.Perks.Lucky", "33"))); @@ -170,8 +165,8 @@ public class Roll extends AcrobaticsSubSkill { } @NotNull - private Probability getRollProbability(Player player) { - return ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, player); + private Probability getRollProbability(McMMOPlayer mmoPlayer) { + return ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer); } @Override @@ -189,8 +184,9 @@ public class Roll extends AcrobaticsSubSkill { return true; } - private boolean canRoll(Player player) { - return RankUtils.hasUnlockedSubskill(player, SubSkillType.ACROBATICS_ROLL) && Permissions.isSubSkillEnabled(player, SubSkillType.ACROBATICS_ROLL); + private boolean canRoll(McMMOPlayer mmoPlayer) { + return RankUtils.hasUnlockedSubskill(mmoPlayer.getPlayer(), SubSkillType.ACROBATICS_ROLL) + && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), SubSkillType.ACROBATICS_ROLL); } /** @@ -200,43 +196,41 @@ public class Roll extends AcrobaticsSubSkill { * @return the modified event damage if the ability was successful, the original event damage otherwise */ @VisibleForTesting - public double rollCheck(Player player, McMMOPlayer mcMMOPlayer, double damage) { + public double rollCheck(McMMOPlayer mmoPlayer, double damage) { + int skillLevel = mmoPlayer.getSkillLevel(getPrimarySkill()); - int skillLevel = mcMMOPlayer.getSkillLevel(getPrimarySkill()); - - if (player.isSneaking()) { - return gracefulRollCheck(player, mcMMOPlayer, damage, skillLevel); + if (mmoPlayer.getPlayer().isSneaking()) { + return gracefulRollCheck(mmoPlayer, damage, skillLevel); } double modifiedDamage = calculateModifiedRollDamage(damage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold()); - if (!isFatal(player, modifiedDamage) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_ROLL, player)) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Roll.Text"); - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS); - //player.sendMessage(LocaleLoader.getString("Acrobatics.Roll.Text")); + if (!isFatal(mmoPlayer, modifiedDamage) + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_ROLL, mmoPlayer)) { + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Roll.Text"); + SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS); + //mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Acrobatics.Roll.Text")); - //if (!SkillUtils.cooldownExpired((long) mcMMOPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); + //if (!SkillUtils.cooldownExpired((long) mcMMOmmoPlayer.getPlayer().getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, true), XPGainReason.PVE); //} - addFallLocation(player); + addFallLocation(mmoPlayer); return modifiedDamage; - } - else if (!isFatal(player, damage)) { - //if (!SkillUtils.cooldownExpired((long) mcMMOPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, false), XPGainReason.PVE); + } else if (!isFatal(mmoPlayer, damage)) { + //if (!SkillUtils.cooldownExpired((long) mmoPlayer.getTeleportATS(), Config.getInstance().getXPAfterTeleportCooldown())) { + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); //} } - addFallLocation(player); + addFallLocation(mmoPlayer); return damage; } - private int getActivationChance(McMMOPlayer mcMMOPlayer) { - return PerksUtils.handleLuckyPerks(mcMMOPlayer.getPlayer(), getPrimarySkill()); + private int getActivationChance(McMMOPlayer mmoPlayer) { + return PerksUtils.handleLuckyPerks(mmoPlayer, getPrimarySkill()); } /** @@ -245,37 +239,35 @@ public class Roll extends AcrobaticsSubSkill { * @param damage The amount of damage initially dealt by the event * @return the modified event damage if the ability was successful, the original event damage otherwise */ - private double gracefulRollCheck(Player player, McMMOPlayer mcMMOPlayer, double damage, int skillLevel) { + private double gracefulRollCheck(McMMOPlayer mmoPlayer, double damage, int skillLevel) { double modifiedDamage = calculateModifiedRollDamage(damage, mcMMO.p.getAdvancedConfig().getRollDamageThreshold() * 2); - Probability gracefulProbability = getGracefulProbability(player); + final Probability gracefulProbability = getGracefulProbability(mmoPlayer); - if (!isFatal(player, modifiedDamage) + if (!isFatal(mmoPlayer, modifiedDamage) //TODO: Graceful isn't sending out an event - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, player, gracefulProbability)) - { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); - SoundManager.sendCategorizedSound(player, player.getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, true), XPGainReason.PVE); + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.ACROBATICS, mmoPlayer, gracefulProbability)) { + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Acrobatics.Ability.Proc"); + SoundManager.sendCategorizedSound(mmoPlayer.getPlayer(), mmoPlayer.getPlayer().getLocation(), SoundType.ROLL_ACTIVATED, SoundCategory.PLAYERS,0.5F); + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, true), XPGainReason.PVE); - addFallLocation(player); + addFallLocation(mmoPlayer); return modifiedDamage; - } - else if (!isFatal(player, damage)) { - if(!isExploiting(player) && mcMMOPlayer.getAcrobaticsManager().canGainRollXP()) - SkillUtils.applyXpGain(mcMMOPlayer, getPrimarySkill(), calculateRollXP(player, damage, false), XPGainReason.PVE); + } else if (!isFatal(mmoPlayer, damage)) { + if (!isExploiting(mmoPlayer) && mmoPlayer.getAcrobaticsManager().canGainRollXP()) + SkillUtils.applyXpGain(mmoPlayer, getPrimarySkill(), calculateRollXP(mmoPlayer, damage, false), XPGainReason.PVE); - addFallLocation(player); + addFallLocation(mmoPlayer); } return damage; } @NotNull - public static Probability getGracefulProbability(Player player) { - double gracefulOdds = ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, player).getValue() * 2; - return Probability.ofPercent(gracefulOdds); + public static Probability getGracefulProbability(McMMOPlayer mmoPlayer) { + double gracefulOdds = ProbabilityUtil.getSubSkillProbability(SubSkillType.ACROBATICS_ROLL, mmoPlayer).getValue() * 2; + return Probability.ofValue(gracefulOdds); } /** @@ -284,24 +276,21 @@ public class Roll extends AcrobaticsSubSkill { * * @return true if exploits are detected, false otherwise */ - private boolean isExploiting(Player player) { + private boolean isExploiting(McMMOPlayer mmoPlayer) { if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { return false; } - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - - if (ItemUtils.hasItemInEitherHand(player, Material.ENDER_PEARL) || player.isInsideVehicle()) { - if(mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); + if (ItemUtils.hasItemInEitherHand(mmoPlayer.getPlayer(), Material.ENDER_PEARL) || mmoPlayer.getPlayer().isInsideVehicle()) { + if (mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Ender Pearl or Inside Vehicle"); } return true; } - if(UserManager.getPlayer(player).getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(player))) - { - if(mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); + if (mmoPlayer.getAcrobaticsManager().hasFallenInLocationBefore(getBlockLocation(mmoPlayer))) { + if (mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Acrobatics XP Prevented: Fallen in location before"); } return true; @@ -310,14 +299,14 @@ public class Roll extends AcrobaticsSubSkill { return false; //NOT EXPLOITING } - private float calculateRollXP(Player player, double damage, boolean isRoll) { + private float calculateRollXP(McMMOPlayer mmoPlayer, double damage, boolean isRoll) { //Clamp Damage to account for insane DRs damage = Math.min(20, damage); - ItemStack boots = player.getInventory().getBoots(); + ItemStack boots = mmoPlayer.getPlayer().getInventory().getBoots(); float xp = (float) (damage * (isRoll ? ExperienceConfig.getInstance().getRollXPModifier() : ExperienceConfig.getInstance().getFallXPModifier())); - if (boots != null && boots.containsEnchantment(Enchantment.PROTECTION_FALL)) { + if (boots != null && boots.containsEnchantment(mcMMO.p.getEnchantmentMapper().getFeatherFalling())) { xp *= ExperienceConfig.getInstance().getFeatherFallXPModifier(); } @@ -328,8 +317,8 @@ public class Roll extends AcrobaticsSubSkill { return Math.max(damage - damageThreshold, 0.0); } - private boolean isFatal(Player player, double damage) { - return player.getHealth() - damage <= 0; + private boolean isFatal(McMMOPlayer mmoPlayer, double damage) { + return mmoPlayer.getPlayer().getHealth() - damage <= 0; } /** @@ -345,103 +334,50 @@ public class Roll extends AcrobaticsSubSkill { /** * Prints detailed info about this subskill to the player * - * @param player the target player + * @param mmoPlayer the target player */ @Override - public void printInfo(Player player) { + public void printInfo(McMMOPlayer mmoPlayer) { //Header - super.printInfo(player); + super.printInfo(mmoPlayer); //Start the description string. //player.sendMessage(getDescription()); //Player stats - player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Stats", - LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(player)))); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.MmoInfo.Stats", + LocaleLoader.getString("Acrobatics.SubSkill.Roll.Stats", getStats(mmoPlayer)))); //Mechanics - player.sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mechanics")); - player.sendMessage(getMechanics()); + mmoPlayer.getPlayer().sendMessage(LocaleLoader.getString("Commands.MmoInfo.Mechanics")); + mmoPlayer.getPlayer().sendMessage(getMechanics()); } - /** - * Returns a collection of strings about how a skill works - * Used in the MMO Info command - * - * @return - */ @Override public String getMechanics() { - //Vars passed to locale - //0 = chance to roll at half max level - //1 = chance to roll with grace at half max level - //2 = level where maximum bonus is reached - //3 = additive chance to succeed per level - //4 = damage threshold when rolling - //5 = damage threshold when rolling with grace - //6 = half of level where maximum bonus is reached - /* - Roll: - # ChanceMax: Maximum chance of rolling when on or higher - # MaxBonusLevel: On this level or higher, the roll chance will not go higher than - # DamageThreshold: The max damage a player can negate with a roll - ChanceMax: 100.0 - MaxBonusLevel: 100 - DamageThreshold: 7.0 - */ - return "Under Construction: This will work in a future update."; -// -// double rollChanceHalfMax, graceChanceHalfMax, damageThreshold, chancePerLevel; -// -// //Chance to roll at half max skill -// RandomChanceSkill rollHalfMaxSkill = new RandomChanceSkill(null, subSkillType); -// int halfMaxSkillValue = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL)/2; -// rollHalfMaxSkill.setSkillLevel(halfMaxSkillValue); -// -// //Chance to graceful roll at full skill -// RandomChanceSkill rollGraceHalfMaxSkill = new RandomChanceSkill(null, subSkillType); -// rollGraceHalfMaxSkill.setSkillLevel(halfMaxSkillValue * 2); //Double the effective odds -// -// //Chance to roll per level -// RandomChanceSkill rollOneSkillLevel = new RandomChanceSkill(null, subSkillType); -// rollGraceHalfMaxSkill.setSkillLevel(1); //Level 1 skill -// -// //Chance Stat Calculations -// rollChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollHalfMaxSkill); -// graceChanceHalfMax = RandomChanceUtil.getRandomChanceExecutionChance(rollGraceHalfMaxSkill); -// damageThreshold = mcMMO.p.getAdvancedConfig().getRollDamageThreshold(); -// -// chancePerLevel = RandomChanceUtil.getRandomChanceExecutionChance(rollOneSkillLevel); -// -// double maxLevel = mcMMO.p.getAdvancedConfig().getMaxBonusLevel(SubSkillType.ACROBATICS_ROLL); -// -// return LocaleLoader.getString("Acrobatics.SubSkill.Roll.Mechanics", rollChanceHalfMax, graceChanceHalfMax, maxLevel, chancePerLevel, damageThreshold, damageThreshold * 2,halfMaxSkillValue); } /** * Get an array of various stats for a player * - * @param player target player + * @param mmoPlayer target player * @return stat array for target player for this skill */ @Override - public Double[] getStats(Player player) - { - double playerChanceRoll = ProbabilityUtil.getSubSkillProbability(subSkillType, player).getValue(); + public Double[] getStats(McMMOPlayer mmoPlayer) { + double playerChanceRoll = ProbabilityUtil.getSubSkillProbability(subSkillType, mmoPlayer).getValue(); double playerChanceGrace = playerChanceRoll * 2; - double gracefulOdds = ProbabilityUtil.getSubSkillProbability(subSkillType, player).getValue() * 2; + double gracefulOdds = ProbabilityUtil.getSubSkillProbability(subSkillType, mmoPlayer).getValue() * 2; return new Double[]{ playerChanceRoll, playerChanceGrace }; } - public void addFallLocation(@NotNull Player player) - { - UserManager.getPlayer(player).getAcrobaticsManager().addLocationToFallMap(getBlockLocation(player)); + public void addFallLocation(@NotNull McMMOPlayer mmoPlayer) { + mmoPlayer.getAcrobaticsManager().addLocationToFallMap(getBlockLocation(mmoPlayer)); } - public @NotNull Location getBlockLocation(@NotNull Player player) - { - return player.getLocation().getBlock().getLocation(); + public @NotNull Location getBlockLocation(@NotNull McMMOPlayer mmoPlayer) { + return mmoPlayer.getPlayer().getLocation().getBlock().getLocation(); } } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java index 33d0e9874..9a3c49e30 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/interfaces/SubSkill.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.datatypes.skills.subskills.interfaces; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.interfaces.Skill; import net.kyori.adventure.text.TextComponent; import org.bukkit.entity.Player; @@ -19,10 +20,10 @@ public interface SubSkill extends Skill { /** * Get an array of various stats for a player - * @param player target player + * @param mmoPlayer target player * @return stat array for target player for this skill */ - Double[] getStats(Player player); + Double[] getStats(McMMOPlayer mmoPlayer); /** * Checks if a player has permission to use this skill @@ -59,9 +60,9 @@ public interface SubSkill extends Skill { /** * Adds detailed stats specific to this skill * @param componentBuilder target component builder - * @param player owner of this skill + * @param mmoPlayer owner of this skill */ - void addStats(TextComponent.Builder componentBuilder, Player player); + void addStats(TextComponent.Builder componentBuilder, McMMOPlayer mmoPlayer); /** * Whether this subskill is enabled @@ -71,7 +72,7 @@ public interface SubSkill extends Skill { /** * Prints detailed info about this subskill to the player - * @param player the target player + * @param mmoPlayer the target player */ - void printInfo(Player player); + void printInfo(McMMOPlayer mmoPlayer); } diff --git a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java index f92155a6a..1c39fed2f 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java +++ b/src/main/java/com/gmail/nossr50/datatypes/skills/subskills/taming/TamingSummon.java @@ -36,7 +36,7 @@ public class TamingSummon { entityType = EntityType.HORSE; break; case CAT: - if(shouldSpawnCatInsteadOfOcelot()) { + if (shouldSpawnCatInsteadOfOcelot()) { //Server is on 1.14 or above entityType = EntityType.CAT; } else { diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java index 69feb7b9b..efe7d1f9c 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/FishingTreasureBook.java @@ -30,7 +30,7 @@ public class FishingTreasureBook extends FishingTreasure { LogUtils.debug(mcMMO.p.getLogger(), "Registering enchantments for Fishing Book..."); for(Enchantment enchantment : Enchantment.values()) { - if(isEnchantAllowed(enchantment)) { + if (isEnchantAllowed(enchantment)) { addAllLegalEnchants(enchantment); } } @@ -66,9 +66,9 @@ public class FishingTreasureBook extends FishingTreasure { } private boolean isEnchantAllowed(@NotNull Enchantment enchantment) { - if(whiteListedEnchantments != null && !whiteListedEnchantments.isEmpty()) { + if (whiteListedEnchantments != null && !whiteListedEnchantments.isEmpty()) { return whiteListedEnchantments.contains(enchantment); - } else if(blackListedEnchantments != null && !blackListedEnchantments.isEmpty()) { + } else if (blackListedEnchantments != null && !blackListedEnchantments.isEmpty()) { return !blackListedEnchantments.contains(enchantment); } else { return true; diff --git a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java index 4666b32b1..0ff04bdbd 100644 --- a/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java +++ b/src/main/java/com/gmail/nossr50/datatypes/treasure/Rarity.java @@ -12,7 +12,7 @@ public enum Rarity { COMMON; public static @NotNull Rarity getRarity(@NotNull String string) { - if(string.equalsIgnoreCase("Records")) { + if (string.equalsIgnoreCase("Records")) { mcMMO.p.getLogger().severe("Entries in fishing treasures have Records set as rarity, however Records was renamed to Mythic. Please update your treasures to read MYTHIC instead of RECORDS for rarity, or delete the config file to regenerate a new one."); return Rarity.MYTHIC; //People that copy paste their configs will have Records interpretted as Mythic } diff --git a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java index 44ad7d078..f278143cd 100644 --- a/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java +++ b/src/main/java/com/gmail/nossr50/events/experience/McMMOPlayerExperienceEvent.java @@ -30,7 +30,7 @@ public abstract class McMMOPlayerExperienceEvent extends PlayerEvent implements super(player); this.skill = skill; - if(UserManager.getPlayer(player) != null) { + if (UserManager.getPlayer(player) != null) { this.skillLevel = UserManager.getPlayer(player).getSkillLevel(skill); } else { this.skillLevel = 0; diff --git a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java index e03a8a4f7..a3f31598b 100644 --- a/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java +++ b/src/main/java/com/gmail/nossr50/events/scoreboard/McMMOScoreboardEvent.java @@ -18,8 +18,7 @@ abstract public class McMMOScoreboardEvent extends Event { private final ScoreboardEventReason scoreboardEventReason; - public McMMOScoreboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) - { + public McMMOScoreboardEvent(Scoreboard targetBoard, Scoreboard currentBoard, Player targetPlayer, ScoreboardEventReason scoreboardEventReason) { this.scoreboardEventReason = scoreboardEventReason; this.targetBoard = targetBoard; this.currentBoard = currentBoard; diff --git a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java index 6238886c0..99059ff19 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/McMMOPlayerSkillEvent.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.events.skills; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; @@ -7,19 +8,35 @@ import org.bukkit.event.HandlerList; import org.bukkit.event.player.PlayerEvent; import org.jetbrains.annotations.NotNull; +import static java.util.Objects.requireNonNull; + /** * Generic event for mcMMO skill handling. */ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { protected @NotNull PrimarySkillType skill; protected int skillLevel; + protected McMMOPlayer mmoPlayer; + @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerSkillEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { super(player); + McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + requireNonNull(mmoPlayer, "Player not found in UserManager," + + "contact the dev and tell them to use the constructor for" + + " McMMOPlayerSkillEvent(McMMOPlayer, PrimarySkillType) instead"); this.skill = skill; this.skillLevel = UserManager.getPlayer(player).getSkillLevel(skill); } + protected McMMOPlayerSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType) { + super(mmoPlayer.getPlayer()); + requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); + requireNonNull(primarySkillType, "primarySkillType cannot be null"); + this.skill = primarySkillType; + this.skillLevel = mmoPlayer.getSkillLevel(primarySkillType); + } + /** * @return The skill involved in this event */ @@ -37,6 +54,15 @@ public abstract class McMMOPlayerSkillEvent extends PlayerEvent { /** Rest of file is required boilerplate for custom events **/ private static final HandlerList handlers = new HandlerList(); + /** + * Returns the {@link McMMOPlayer} associated with this event. + * + * @return The {@link McMMOPlayer} associated with this event. + */ + public @NotNull McMMOPlayer getMcMMOPlayer() { + return mmoPlayer; + } + @Override public @NotNull HandlerList getHandlers() { return handlers; diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java index 7b0db958b..707981c9c 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityActivateEvent.java @@ -1,14 +1,24 @@ package com.gmail.nossr50.events.skills.abilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import java.util.Objects; + public class McMMOPlayerAbilityActivateEvent extends McMMOPlayerAbilityEvent implements Cancellable { private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerAbilityActivateEvent(Player player, PrimarySkillType skill) { - super(player, skill); + super(Objects.requireNonNull(UserManager.getPlayer(player)), skill); + cancelled = false; + } + + public McMMOPlayerAbilityActivateEvent(McMMOPlayer mmoPlayer, PrimarySkillType skill) { + super(mmoPlayer, skill); cancelled = false; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java index 384b61c92..bf55a43ab 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityDeactivateEvent.java @@ -1,10 +1,20 @@ package com.gmail.nossr50.events.skills.abilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; public class McMMOPlayerAbilityDeactivateEvent extends McMMOPlayerAbilityEvent { - public McMMOPlayerAbilityDeactivateEvent(Player player, PrimarySkillType skill) { - super(player, skill); + @Deprecated(forRemoval = true, since = "2.2.010") + public McMMOPlayerAbilityDeactivateEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { + this(requireNonNull(UserManager.getPlayer(player)), skill); + } + + public McMMOPlayerAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType skill) { + super(mmoPlayer, skill); } } diff --git a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java index 08d7dc2b2..42e5fd9a5 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/abilities/McMMOPlayerAbilityEvent.java @@ -1,16 +1,38 @@ package com.gmail.nossr50.events.skills.abilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; +import java.util.Objects; + public class McMMOPlayerAbilityEvent extends McMMOPlayerSkillEvent { private final SuperAbilityType ability; + /** + * Create a new McMMOPlayerAbilityEvent. + * + * @param player The player involved in this event + * @param skill The skill involved in this event + * @deprecated Use {@link #McMMOPlayerAbilityEvent(McMMOPlayer, PrimarySkillType)} instead + */ + @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerAbilityEvent(Player player, PrimarySkillType skill) { - super(player, skill); + super(Objects.requireNonNull(UserManager.getPlayer(player)), skill); + ability = mcMMO.p.getSkillTools().getSuperAbility(skill); + } + + /** + * Create a new McMMOPlayerAbilityEvent. + * @param mmoPlayer The McMMOPlayer involved in this event + * @param skill The skill involved in this event + */ + protected McMMOPlayerAbilityEvent(McMMOPlayer mmoPlayer, PrimarySkillType skill) { + super(mmoPlayer, skill); ability = mcMMO.p.getSkillTools().getSuperAbility(skill); } diff --git a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java index ca62829cb..cd3dd032a 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerBrewEvent.java @@ -1,24 +1,36 @@ package com.gmail.nossr50.events.skills.alchemy; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; public class McMMOPlayerBrewEvent extends McMMOPlayerSkillEvent implements Cancellable { private final BlockState brewingStand; private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerBrewEvent(Player player, BlockState brewingStand) { - super(player, PrimarySkillType.ALCHEMY); + super(requireNonNull(UserManager.getPlayer(player)), PrimarySkillType.ALCHEMY); this.brewingStand = brewingStand; cancelled = false; } + public McMMOPlayerBrewEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull BlockState brewingStand) { + super(mmoPlayer, PrimarySkillType.ALCHEMY); + this.brewingStand = requireNonNull(brewingStand); + cancelled = false; + } + public boolean isCancelled() { return cancelled; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java index c4dbcc7d3..385cbaec0 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/alchemy/McMMOPlayerCatalysisEvent.java @@ -1,17 +1,28 @@ package com.gmail.nossr50.events.skills.alchemy; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import static java.util.Objects.requireNonNull; + public class McMMOPlayerCatalysisEvent extends McMMOPlayerSkillEvent implements Cancellable { private double speed; private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerCatalysisEvent(Player player, double speed) { - super(player, PrimarySkillType.ALCHEMY); + super(requireNonNull(UserManager.getPlayer(player)), PrimarySkillType.ALCHEMY); + this.speed = speed; + cancelled = false; + } + + public McMMOPlayerCatalysisEvent(McMMOPlayer mmoPlayer, double speed) { + super(mmoPlayer, PrimarySkillType.ALCHEMY); this.speed = speed; cancelled = false; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java index 96cde8b6b..363b10927 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingEvent.java @@ -1,15 +1,23 @@ package com.gmail.nossr50.events.skills.fishing; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; public class McMMOPlayerFishingEvent extends McMMOPlayerSkillEvent implements Cancellable { private boolean cancelled; + @Deprecated(forRemoval = true, since = "2.2.010") protected McMMOPlayerFishingEvent(Player player) { - super(player, PrimarySkillType.FISHING); + super(UserManager.getPlayer(player), PrimarySkillType.FISHING); + cancelled = false; + } + + protected McMMOPlayerFishingEvent(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.FISHING); cancelled = false; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java index dba01b751..0437e2fc8 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerFishingTreasureEvent.java @@ -1,23 +1,34 @@ package com.gmail.nossr50.events.skills.fishing; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import static java.util.Objects.requireNonNull; public class McMMOPlayerFishingTreasureEvent extends McMMOPlayerFishingEvent { private ItemStack treasure; private int xp; + @Deprecated(forRemoval = true, since = "2.2.010") public McMMOPlayerFishingTreasureEvent(Player player, ItemStack treasure, int xp) { - super(player); + this(requireNonNull(UserManager.getPlayer(player)), treasure, xp); + } + + public McMMOPlayerFishingTreasureEvent(@NotNull McMMOPlayer mmoPlayer, @Nullable ItemStack treasure, int xp) { + super(mmoPlayer); this.treasure = treasure; this.xp = xp; } - public ItemStack getTreasure() { + public @Nullable ItemStack getTreasure() { return treasure; } - public void setTreasure(ItemStack item) { + public void setTreasure(@Nullable ItemStack item) { this.treasure = item; } diff --git a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java index decd27ad5..93cc5c8c8 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/fishing/McMMOPlayerMagicHunterEvent.java @@ -1,20 +1,32 @@ package com.gmail.nossr50.events.skills.fishing; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import java.util.HashMap; import java.util.Map; -public class McMMOPlayerMagicHunterEvent extends McMMOPlayerFishingTreasureEvent { - private final Map enchants; +import static java.util.Objects.requireNonNull; - public McMMOPlayerMagicHunterEvent(Player player, ItemStack treasure, int xp, Map enchants) { - super(player, treasure, xp); - this.enchants = enchants; +public class McMMOPlayerMagicHunterEvent extends McMMOPlayerFishingTreasureEvent { + private final Map enchants = new HashMap<>(); + + @Deprecated(forRemoval = true, since = "2.2.010") + public McMMOPlayerMagicHunterEvent(@NotNull Player player, @NotNull ItemStack treasure, int xp, @NotNull Map enchants) { + this(requireNonNull(UserManager.getPlayer(player)), treasure, xp, enchants); } - public Map getEnchantments() { + public McMMOPlayerMagicHunterEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull ItemStack treasure, int xp, @NotNull Map enchants) { + super(mmoPlayer, treasure, xp); + requireNonNull(enchants, "enchants cannot be null"); + this.enchants.putAll(enchants); + } + + public @NotNull Map getEnchantments() { return enchants; } } diff --git a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java index 5445bbfcd..273a6e442 100644 --- a/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java +++ b/src/main/java/com/gmail/nossr50/events/skills/secondaryabilities/SubSkillEvent.java @@ -1,11 +1,16 @@ package com.gmail.nossr50.events.skills.secondaryabilities; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.events.skills.McMMOPlayerSkillEvent; import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; +import org.jetbrains.annotations.NotNull; + +import static java.util.Objects.requireNonNull; public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable { private SubSkillType subSkillType; @@ -16,9 +21,20 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable * Only skills using the old system will fire this event * @param player target player * @param subSkillType target subskill + * @deprecated Use {@link #SubSkillEvent(McMMOPlayer, SubSkillType)} instead */ - public SubSkillEvent(Player player, SubSkillType subSkillType) { - super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); + @Deprecated(forRemoval = true, since = "2.2.010") + public SubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType) { + this(requireNonNull(UserManager.getPlayer(player)), subSkillType); + } + + /** + * Only skills using the old system will fire this event + * @param mmoPlayer target player + * @param subSkillType target subskill + */ + public SubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { + super(mmoPlayer, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); this.subSkillType = subSkillType; } @@ -28,15 +44,30 @@ public class SubSkillEvent extends McMMOPlayerSkillEvent implements Cancellable * @param subSkillType target subskill * @param resultModifier a value multiplied against the final result of the dice roll, typically between 0-1.0 */ - public SubSkillEvent(Player player, SubSkillType subSkillType, double resultModifier) { + @Deprecated(forRemoval = true, since = "2.2.010") + public SubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType, double resultModifier) { + this(requireNonNull(UserManager.getPlayer(player)), subSkillType, resultModifier); + } + + /** + * Only skills using the old system will fire this event + * @param player target player + * @param subSkillType target subskill + * @param resultModifier a value multiplied against the final result of the dice roll, typically between 0-1.0 + */ + public SubSkillEvent(@NotNull McMMOPlayer player, @NotNull SubSkillType subSkillType, double resultModifier) { super(player, mcMMO.p.getSkillTools().getPrimarySkillBySubSkill(subSkillType)); - this.subSkillType = subSkillType; + this.subSkillType = requireNonNull(subSkillType, "subSkillType cannot be null"); this.resultModifier = resultModifier; } - public SubSkillEvent(Player player, AbstractSubSkill abstractSubSkill) - { - super(player, abstractSubSkill.getPrimarySkill()); + @Deprecated(forRemoval = true, since = "2.2.010") + public SubSkillEvent(@NotNull Player player, @NotNull AbstractSubSkill abstractSubSkill) { + this(requireNonNull(UserManager.getPlayer(player)), abstractSubSkill); + } + + public SubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull AbstractSubSkill abstractSubSkill) { + super(mmoPlayer, abstractSubSkill.getPrimarySkill()); } public double getResultModifier() { diff --git a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java index 63585b917..1c648b767 100644 --- a/src/main/java/com/gmail/nossr50/listeners/BlockListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/BlockListener.java @@ -47,11 +47,10 @@ public class BlockListener implements Listener { } @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = false) - public void onBlockDropItemEvent(BlockDropItemEvent event) - { + public void onBlockDropItemEvent(BlockDropItemEvent event) { //Make sure we clean up metadata on these blocks - if(event.isCancelled()) { - if(event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (event.isCancelled()) { + if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) event.getBlock().removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, plugin); return; } @@ -59,7 +58,7 @@ public class BlockListener implements Listener { int tileEntityTolerance = 1; // beetroot hotfix, potentially other plants may need this fix - if(event.getBlockState().getType() == Material.BEETROOTS) + if (event.getBlockState().getType() == Material.BEETROOTS) tileEntityTolerance = 2; //Track how many "things" are being dropped @@ -72,34 +71,33 @@ public class BlockListener implements Listener { uniqueMaterials.add(item.getItemStack().getType()); //Count blocks as a second failsafe - if(item.getItemStack().getType().isBlock()) + if (item.getItemStack().getType().isBlock()) blockCount++; } - if(uniqueMaterials.size() > tileEntityTolerance) { + if (uniqueMaterials.size() > tileEntityTolerance) { //Too many things are dropping, assume tile entities might be duped //Technically this would also prevent something like coal from being bonus dropped if you placed a TE above a coal ore when mining it but that's pretty edge case and this is a good solution for now dontRewardTE = true; } //If there are more than one block in the item list we can't really trust it and will back out of rewarding bonus drops - if(blockCount <= 1) { - for(Item item : event.getItems()) - { + if (blockCount <= 1) { + for(Item item : event.getItems()) { ItemStack is = new ItemStack(item.getItemStack()); - if(is.getAmount() <= 0) + if (is.getAmount() <= 0) continue; //TODO: Ignore this abomination its rewritten in 2.2 - if(!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) + if (!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, is.getType()) && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.HERBALISM, is.getType()) && !mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, is.getType())) continue; //If we suspect TEs might be duped only reward block - if(dontRewardTE) { - if(!is.getType().isBlock()) { + if (dontRewardTE) { + if (!is.getType().isBlock()) { continue; } } @@ -115,7 +113,7 @@ public class BlockListener implements Listener { } } - if(event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (event.getBlock().hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) event.getBlock().removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, plugin); } @@ -127,10 +125,10 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonExtend(BlockPistonExtendEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; - if(!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { + if (!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { return; } @@ -155,10 +153,10 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onBlockPistonRetract(BlockPistonRetractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; - if(!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { + if (!ExperienceConfig.getInstance().isPistonCheatingPrevented()) { return; } @@ -167,12 +165,12 @@ public class BlockListener implements Listener { Block movedBlock = event.getBlock().getRelative(direction); //Spigot makes bad things happen in its API - if(BlockUtils.isWithinWorldBounds(movedBlock)) { + if (BlockUtils.isWithinWorldBounds(movedBlock)) { BlockUtils.setUnnaturalBlock(movedBlock); } for (Block block : event.getBlocks()) { - if(BlockUtils.isWithinWorldBounds(block) && BlockUtils.isWithinWorldBounds(block.getRelative(direction))) { + if (BlockUtils.isWithinWorldBounds(block) && BlockUtils.isWithinWorldBounds(block.getRelative(direction))) { Block relativeBlock = block.getRelative(direction); BlockUtils.setUnnaturalBlock(relativeBlock); } @@ -186,18 +184,17 @@ public class BlockListener implements Listener { * @param event The event to watch */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEntityBlockFormEvent(EntityBlockFormEvent event) - { + public void onEntityBlockFormEvent(EntityBlockFormEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; BlockState blockState = event.getNewState(); - if(ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) { + if (ExperienceConfig.getInstance().isSnowExploitPrevented() && BlockUtils.shouldBeWatched(blockState)) { Block block = blockState.getBlock(); - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { BlockUtils.setUnnaturalBlock(block); } } @@ -207,20 +204,19 @@ public class BlockListener implements Listener { * Does not monitor stuff like a falling block replacing a liquid */ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockFormEvent(BlockFormEvent event) - { + public void onBlockFormEvent(BlockFormEvent event) { World world = event.getBlock().getWorld(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(world)) + if (WorldBlacklist.isWorldBlacklisted(world)) return; - if(ExperienceConfig.getInstance().preventStoneLavaFarming()) { + if (ExperienceConfig.getInstance().preventStoneLavaFarming()) { BlockState newState = event.getNewState(); - if(newState.getType() != Material.OBSIDIAN && ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, newState.getBlockData())) { + if (newState.getType() != Material.OBSIDIAN && ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, newState.getBlockData())) { Block block = newState.getBlock(); - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { BlockUtils.setUnnaturalBlock(block); } } @@ -241,11 +237,11 @@ public class BlockListener implements Listener { // if (!Tag.LOGS.isTagged(event.getBlockReplacedState().getType()) || !Tag.LOGS.isTagged(event.getBlockPlaced().getType())) /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(block.getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(block.getWorld())) { return; } - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { //NOTE: BlockMultiPlace has its own logic so don't handle anything that would overlap if (!(event instanceof BlockMultiPlaceEvent)) { BlockUtils.setUnnaturalBlock(block); @@ -261,13 +257,12 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; if (blockState.getType() == Repair.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.REPAIR)) { mcMMOPlayer.getRepairManager().placedAnvilCheck(); - } - else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) { + } else if (blockState.getType() == Salvage.anvilMaterial && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SALVAGE)) { mcMMOPlayer.getSalvageManager().placedAnvilCheck(); } } @@ -284,10 +279,10 @@ public class BlockListener implements Listener { Block block = blockState.getBlock(); /* Check if the blocks placed should be monitored so they do not give out XP in the future */ - if(BlockUtils.isWithinWorldBounds(block)) { + if (BlockUtils.isWithinWorldBounds(block)) { //Updated: 10/5/2021 //Note: For some reason Azalea trees trigger this event but no other tree does (as of 10/5/2021) but if this changes in the future we may need to update this - if(BlockUtils.isPartOfTree(event.getBlockPlaced())) { + if (BlockUtils.isPartOfTree(event.getBlockPlaced())) { return; } @@ -305,12 +300,12 @@ public class BlockListener implements Listener { World world = block.getWorld(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(world)) + if (WorldBlacklist.isWorldBlacklisted(world)) return; // Minecraft is dumb, the events still throw when a plant "grows" higher than the max block height. Even though no new block is created - if(BlockUtils.isWithinWorldBounds(block)) { - mcMMO.getPlaceStore().setFalse(block); + if (BlockUtils.isWithinWorldBounds(block)) { + mcMMO.getUserBlockTracker().setEligible(block); } } @@ -328,15 +323,14 @@ public class BlockListener implements Listener { return; } - if(WorldBlacklist.isWorldBlacklisted(block.getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(block.getWorld())) { BlockUtils.cleanupBlockMetadata(block); return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) { BlockUtils.cleanupBlockMetadata(block); return; } @@ -364,7 +358,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Check if profile is loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { /* Remove metadata from placed watched blocks */ BlockUtils.cleanupBlockMetadata(block); @@ -400,19 +394,18 @@ public class BlockListener implements Listener { else if (BlockUtils.affectedBySuperBreaker(blockState) && (ItemUtils.isPickaxe(heldItem) || ItemUtils.isHoe(heldItem)) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MINING) - && !mcMMO.getPlaceStore().isTrue(blockState)) { + && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { MiningManager miningManager = mcMMOPlayer.getMiningManager(); miningManager.miningBlockCheck(blockState); } /* WOOD CUTTING */ else if (BlockUtils.hasWoodcuttingXP(blockState) && ItemUtils.isAxe(heldItem) - && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getPlaceStore().isTrue(blockState)) { + && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.WOODCUTTING) && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { WoodcuttingManager woodcuttingManager = mcMMOPlayer.getWoodcuttingManager(); if (woodcuttingManager.canUseTreeFeller(heldItem)) { woodcuttingManager.processTreeFeller(blockState); - } - else { + } else { //Check for XP woodcuttingManager.processWoodcuttingBlockXP(blockState); @@ -422,7 +415,10 @@ public class BlockListener implements Listener { } /* EXCAVATION */ - else if (BlockUtils.affectedByGigaDrillBreaker(blockState) && ItemUtils.isShovel(heldItem) && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) && !mcMMO.getPlaceStore().isTrue(blockState)) { + else if (BlockUtils.affectedByGigaDrillBreaker(blockState) + && ItemUtils.isShovel(heldItem) + && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.EXCAVATION) + && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { ExcavationManager excavationManager = mcMMOPlayer.getExcavationManager(); excavationManager.excavationBlockCheck(blockState); @@ -442,17 +438,16 @@ public class BlockListener implements Listener { */ @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockBreakHigher(BlockBreakEvent event) { - if(event instanceof FakeEvent) + if (event instanceof FakeEvent) return; /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -463,8 +458,7 @@ public class BlockListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -478,8 +472,7 @@ public class BlockListener implements Listener { if (herbalismManager.processHylianLuck(blockState)) { blockState.update(true); event.setCancelled(true); - } - else if (blockState.getType() == Material.FLOWER_POT) { + } else if (blockState.getType() == Material.FLOWER_POT) { blockState.setType(Material.AIR); blockState.update(true); event.setCancelled(true); @@ -509,13 +502,12 @@ public class BlockListener implements Listener { BlockState blockState = event.getBlock().getState(); /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -529,8 +521,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { return; } @@ -544,27 +535,23 @@ public class BlockListener implements Listener { if (mcMMOPlayer.getToolPreparationMode(ToolType.HOE) && ItemUtils.isHoe(heldItem) && (BlockUtils.affectedByGreenTerra(blockState) || BlockUtils.canMakeMossy(blockState)) && Permissions.greenTerra(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.HERBALISM); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.hasWoodcuttingXP(blockState) && Permissions.treeFeller(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.AXE) && ItemUtils.isAxe(heldItem) && BlockUtils.hasWoodcuttingXP(blockState) && Permissions.treeFeller(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.WOODCUTTING); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.PICKAXE) && ItemUtils.isPickaxe(heldItem) && BlockUtils.affectedBySuperBreaker(blockState) && Permissions.superBreaker(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.MINING); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.SHOVEL) && ItemUtils.isShovel(heldItem) && BlockUtils.affectedByGigaDrillBreaker(blockState) && Permissions.gigaDrillBreaker(player)) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.EXCAVATION); - } - else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) + } else if (mcMMOPlayer.getToolPreparationMode(ToolType.FISTS) && heldItem.getType() == Material.AIR && (BlockUtils.affectedByGigaDrillBreaker(blockState) || mcMMO.getMaterialMapStore().isGlass(blockState.getType()) || blockState.getType() == Material.SNOW || BlockUtils.affectedByBlockCracker(blockState) && Permissions.berserk(player))) { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.UNARMED); - if(mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK)) { + if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK)) { if (SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(blockState.getBlock(), player)) { event.setInstaBreak(true); - if(blockState.getType().getKey().getKey().contains("glass")) { + if (blockState.getType().getKey().getKey().contains("glass")) { SoundManager.worldSendSound(player.getWorld(), blockState.getLocation(), SoundType.GLASS); } else { SoundManager.sendSound(player, blockState.getLocation(), SoundType.POP); @@ -592,13 +579,12 @@ public class BlockListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onBlockDamageHigher(BlockDamageEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -615,8 +601,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -633,24 +618,21 @@ public class BlockListener implements Listener { if (mcMMOPlayer.getHerbalismManager().processGreenTerraBlockConversion(blockState)) { blockState.update(true); } - } - else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed())) { + } else if (mcMMOPlayer.getAbilityMode(SuperAbilityType.BERSERK) && (heldItem.getType() == Material.AIR || mcMMO.p.getGeneralConfig().getUnarmedItemsAsUnarmed())) { if (mcMMOPlayer.getUnarmedManager().canUseBlockCracker() && BlockUtils.affectedByBlockCracker(blockState)) { if (EventUtils.simulateBlockBreak(block, player) && mcMMOPlayer.getUnarmedManager().blockCrackerCheck(blockState)) { blockState.update(); } - } - else if (!event.getInstaBreak() && SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(block, player)) { + } else if (!event.getInstaBreak() && SuperAbilityType.BERSERK.blockCheck(blockState) && EventUtils.simulateBlockBreak(block, player)) { event.setInstaBreak(true); - if(blockState.getType().getKey().getKey().contains("glass")) { + if (blockState.getType().getKey().getKey().contains("glass")) { SoundManager.worldSendSound(player.getWorld(), block.getLocation(), SoundType.GLASS); } else { SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } } - } - else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isNonWoodPartOfTree(blockState) && EventUtils.simulateBlockBreak(block, player)) { + } else if (mcMMOPlayer.getWoodcuttingManager().canUseLeafBlower(heldItem) && BlockUtils.isNonWoodPartOfTree(blockState) && EventUtils.simulateBlockBreak(block, player)) { event.setInstaBreak(true); SoundManager.sendSound(player, block.getLocation(), SoundType.POP); } @@ -662,8 +644,7 @@ public class BlockListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -680,50 +661,43 @@ public class BlockListener implements Listener { //TODO: Convert into locale strings private void debugStickDump(Player player, BlockState blockState) { //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } - if(UserManager.getPlayer(player).isDebugMode()) - { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (UserManager.getPlayer(player).isDebugMode()) { + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) player.sendMessage("[mcMMO DEBUG] This block is not natural and does not reward treasures/XP"); - else - { + else { player.sendMessage("[mcMMO DEBUG] This block is considered natural by mcMMO"); UserManager.getPlayer(player).getExcavationManager().printExcavationDebug(player, blockState); } - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (WorldGuardManager.getInstance().hasMainFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard main flag is permitted for this player in this region"); else player.sendMessage("[mcMMO DEBUG] World Guard main flag is DENIED for this player in this region"); - if(WorldGuardManager.getInstance().hasXPFlag(player)) + if (WorldGuardManager.getInstance().hasXPFlag(player)) player.sendMessage("[mcMMO DEBUG] World Guard xp flag is permitted for this player in this region"); else player.sendMessage("[mcMMO DEBUG] World Guard xp flag is not permitted for this player in this region"); } - if(blockState instanceof Furnace furnace) - { - if(mcMMO.getSmeltingTracker().isFurnaceOwned(furnace)) - { - player.sendMessage("[mcMMO DEBUG] This furnace has a registered owner"); - OfflinePlayer furnacePlayer = mcMMO.getSmeltingTracker().getFurnaceOwner(furnace); - if(furnacePlayer != null) - { - player.sendMessage("[mcMMO DEBUG] This furnace is owned by player "+furnacePlayer.getName()); + if (blockState instanceof Furnace || blockState instanceof BrewingStand) { + if (ContainerMetadataUtils.isContainerOwned(blockState)) { + player.sendMessage("[mcMMO DEBUG] This container has a registered owner"); + final OfflinePlayer furnacePlayer = ContainerMetadataUtils.getContainerOwner(blockState); + if (furnacePlayer != null) { + player.sendMessage("[mcMMO DEBUG] This container is owned by player "+furnacePlayer.getName()); } } else - player.sendMessage("[mcMMO DEBUG] This furnace does not have a registered owner"); + player.sendMessage("[mcMMO DEBUG] This container does not have a registered owner"); } - if(ExperienceConfig.getInstance().isExperienceBarsEnabled()) + if (ExperienceConfig.getInstance().isExperienceBarsEnabled()) player.sendMessage("[mcMMO DEBUG] XP bars are enabled, however you should check per-skill settings to make sure those are enabled."); player.sendMessage(ChatColor.RED+"You can turn this debug info off by typing "+ChatColor.GOLD+"/mmodebug"); diff --git a/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java b/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java index 761516deb..defdd6a01 100644 --- a/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/ChunkListener.java @@ -12,7 +12,8 @@ public class ChunkListener implements Listener { @EventHandler(ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { - List matchingEntities = mcMMO.getTransientEntityTracker().getAllTransientEntitiesInChunk(event.getChunk()); + List matchingEntities + = mcMMO.getTransientEntityTracker().getAllTransientEntitiesInChunk(event.getChunk()); for(LivingEntity livingEntity : matchingEntities) { mcMMO.getTransientEntityTracker().removeSummon(livingEntity, null, false); } diff --git a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java index 18edee783..8c3e746ac 100644 --- a/src/main/java/com/gmail/nossr50/listeners/EntityListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/EntityListener.java @@ -8,7 +8,6 @@ import com.gmail.nossr50.datatypes.skills.subskills.interfaces.InteractType; import com.gmail.nossr50.events.fake.FakeEntityTameEvent; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.metadata.MobMetaFlagType; -import com.gmail.nossr50.metadata.MobMetadataService; import com.gmail.nossr50.runnables.TravelingBlockMetaCleanup; import com.gmail.nossr50.skills.archery.Archery; import com.gmail.nossr50.skills.crossbows.Crossbows; @@ -45,11 +44,11 @@ import org.bukkit.metadata.FixedMetadataValue; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.projectiles.ProjectileSource; -import org.jetbrains.annotations.NotNull; + +import static com.gmail.nossr50.util.MobMetadataUtils.*; public class EntityListener implements Listener { private final mcMMO pluginRef; - private final @NotNull MobMetadataService mobMetadataService; /** * We can use this {@link NamespacedKey} for {@link Enchantment} comparisons to @@ -59,18 +58,17 @@ public class EntityListener implements Listener { public EntityListener(final mcMMO pluginRef) { this.pluginRef = pluginRef; - mobMetadataService = mcMMO.getMetadataService().getMobMetadataService(); } @EventHandler(priority = EventPriority.MONITOR) public void onEntityTransform(EntityTransformEvent event) { - if(event.getEntity() instanceof LivingEntity livingEntity) { + if (event.getEntity() instanceof LivingEntity livingEntity) { //Transfer metadata keys from mob-spawned mobs to new mobs - if(mobMetadataService.hasMobFlags(livingEntity)) { + if (hasMobFlags(livingEntity)) { for(Entity entity : event.getTransformedEntities()) { - if(entity instanceof LivingEntity transformedEntity) { - mobMetadataService.addMobFlags(livingEntity, transformedEntity); + if (entity instanceof LivingEntity transformedEntity) { + addMobFlags(livingEntity, transformedEntity); } } } @@ -79,22 +77,20 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTargetEntity(EntityTargetLivingEntityEvent event) { - if(!ExperienceConfig.getInstance().isEndermanEndermiteFarmingPrevented()) + if (!ExperienceConfig.getInstance().isEndermanEndermiteFarmingPrevented()) return; //It's rare but targets can be null sometimes - if(event.getTarget() == null) - { + if (event.getTarget() == null) { return; } //Prevent entities from giving XP if they target endermite - if(event.getTarget() instanceof Endermite) - { - if(event.getEntity() instanceof Enderman enderman) { + if (event.getTarget() instanceof Endermite) { + if (event.getEntity() instanceof Enderman enderman) { - if(!mobMetadataService.hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { - mobMetadataService.flagMetadata(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman); + if (!hasMobFlag(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman)) { + flagMetadata(MobMetaFlagType.EXPLOITED_ENDERMEN, enderman); } } } @@ -103,11 +99,10 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) public void onEntityShootBow(EntityShootBowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Player player) - { + if (event.getEntity() instanceof Player player) { Entity projectile = event.getProjectile(); //Should be noted that there are API changes regarding Arrow from 1.13.2 to current versions of the game @@ -120,7 +115,7 @@ public class EntityListener implements Listener { if (bow == null) return; - if (bow.containsEnchantment(Enchantment.ARROW_INFINITE)) { + if (bow.containsEnchantment(mcMMO.p.getEnchantmentMapper().getInfinity())) { projectile.setMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); } @@ -136,39 +131,38 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onProjectileLaunch(ProjectileLaunchEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity().getShooter() instanceof Player player) - { + if (event.getEntity().getShooter() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if(event.getEntity() instanceof Arrow arrow) { + if (event.getEntity() instanceof Arrow arrow) { // Delayed metadata cleanup in case other cleanup hooks fail CombatUtils.delayArrowMetaCleanup(arrow); // If fired from an item with multi-shot, we need to track - if(ItemUtils.doesPlayerHaveEnchantmentInHands(player, "multishot")) { + if (ItemUtils.doesPlayerHaveEnchantmentInHands(player, "multishot")) { arrow.setMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); } - if(!arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) arrow.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, new FixedMetadataValue(pluginRef, 1.0)); - if(!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) arrow.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, new FixedMetadataValue(pluginRef, arrow.getLocation())); //Check both hands - if(ItemUtils.doesPlayerHaveEnchantmentInHands(player, "piercing")) { + if (ItemUtils.doesPlayerHaveEnchantmentInHands(player, "piercing")) { return; } - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_ARROW_RETRIEVAL, player)) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_ARROW_RETRIEVAL, UserManager.getPlayer(player))) { arrow.setMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, MetadataConstants.MCMMO_METADATA_VALUE); } } @@ -184,7 +178,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityChangeBlock(EntityChangeBlockEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Block block = event.getBlock(); @@ -208,23 +202,21 @@ public class EntityListener implements Listener { if (entity instanceof FallingBlock || entity instanceof Enderman) { boolean isTracked = entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK); - if (mcMMO.getPlaceStore().isTrue(block) && !isTracked) { - mcMMO.getPlaceStore().setFalse(block); + if (mcMMO.getUserBlockTracker().isIneligible(block) && !isTracked) { + mcMMO.getUserBlockTracker().setEligible(block); entity.setMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, MetadataConstants.MCMMO_METADATA_VALUE); TravelingBlockMetaCleanup metaCleanupTask = new TravelingBlockMetaCleanup(entity, pluginRef); mcMMO.p.getFoliaLib().getImpl().runAtEntityTimer(entity, metaCleanupTask, 20, 20*60); //6000 ticks is 5 minutes - } - else if (isTracked) { + } else if (isTracked) { BlockUtils.setUnnaturalBlock(block); entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); } } else if ((block.getType() == Material.REDSTONE_ORE || block.getType().getKey().getKey().equalsIgnoreCase("deepslate_redstone_ore"))) { //Redstone ore fire this event and should be ignored - } - else { - if (mcMMO.getPlaceStore().isTrue(block)) { - mcMMO.getPlaceStore().setFalse(block); + } else { + if (mcMMO.getUserBlockTracker().isIneligible(block)) { + mcMMO.getUserBlockTracker().setEligible(block); } } } @@ -233,16 +225,16 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityCombustByEntityEvent(EntityCombustByEntityEvent event) { //Prevent players from setting fire to each other if they are in the same party - if(event.getEntity() instanceof Player defender) { + if (event.getEntity() instanceof Player defender) { - if(event.getCombuster() instanceof Projectile projectile) { - if(projectile.getShooter() instanceof Player attacker) { - if(checkIfInPartyOrSamePlayer(event, defender, attacker)) { + if (event.getCombuster() instanceof Projectile projectile) { + if (projectile.getShooter() instanceof Player attacker) { + if (checkIfInPartyOrSamePlayer(event, defender, attacker)) { event.setCancelled(true); } } - } else if(event.getCombuster() instanceof Player attacker) { - if(checkIfInPartyOrSamePlayer(event, defender, attacker)) { + } else if (event.getCombuster() instanceof Player attacker) { + if (checkIfInPartyOrSamePlayer(event, defender, attacker)) { event.setCancelled(true); } } @@ -267,18 +259,17 @@ public class EntityListener implements Listener { Entity defender = event.getEntity(); Entity attacker = event.getDamager(); - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(attacker instanceof Player) { + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (attacker instanceof Player) { - if(!WorldGuardManager.getInstance().hasMainFlag((Player) attacker)) { + if (!WorldGuardManager.getInstance().hasMainFlag((Player) attacker)) { return; } - } else if(attacker instanceof Projectile projectile) { + } else if (attacker instanceof Projectile projectile) { - if(projectile.getShooter() instanceof Player) { - if(!WorldGuardManager.getInstance().hasMainFlag((Player) projectile.getShooter())) { + if (projectile.getShooter() instanceof Player) { + if (!WorldGuardManager.getInstance().hasMainFlag((Player) projectile.getShooter())) { return; } } @@ -287,7 +278,7 @@ public class EntityListener implements Listener { } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; } @@ -326,8 +317,7 @@ public class EntityListener implements Listener { if (animalTamer != null && ((OfflinePlayer) animalTamer).isOnline()) { attacker = (Entity) animalTamer; } - } - else if (attacker instanceof TNTPrimed && defender instanceof Player) { + } else if (attacker instanceof TNTPrimed && defender instanceof Player) { if (BlastMining.processBlastMiningExplosion(event, (TNTPrimed) attacker, (Player) defender)) { return; } @@ -336,8 +326,8 @@ public class EntityListener implements Listener { //Friendly fire checks if (defender instanceof Player defendingPlayer) { //If the attacker is a Player or a projectile belonging to a player - if(attacker instanceof Projectile projectile) { - if(projectile.getShooter() instanceof Player attackingPlayer && !attackingPlayer.equals(defendingPlayer)) { + if (attacker instanceof Projectile projectile) { + if (projectile.getShooter() instanceof Player attackingPlayer && !attackingPlayer.equals(defendingPlayer)) { //Check for friendly fire and cancel the event if (checkIfInPartyOrSamePlayer(event, defendingPlayer, attackingPlayer)) { return; @@ -363,9 +353,9 @@ public class EntityListener implements Listener { } //Required setup for processCombatAttack - if(attacker instanceof Projectile) { + if (attacker instanceof Projectile) { ProjectileSource shooter = ((Projectile) attacker).getShooter(); - if(shooter instanceof LivingEntity) { + if (shooter instanceof LivingEntity) { attacker = (LivingEntity) shooter; } } @@ -379,8 +369,8 @@ public class EntityListener implements Listener { * Surprising this kind of thing * */ - if(mcMMO.isProjectKorraEnabled()) { - if(event.getFinalDamage() == 0) { + if (mcMMO.isProjectKorraEnabled()) { + if (event.getFinalDamage() == 0) { return; } } @@ -391,22 +381,22 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = false) public void onEntityDamageMonitor(EntityDamageByEntityEvent entityDamageEvent) { - if(entityDamageEvent.getEntity() instanceof LivingEntity livingEntity) { + if (entityDamageEvent.getEntity() instanceof LivingEntity livingEntity) { - if(entityDamageEvent.getFinalDamage() >= livingEntity.getHealth()) { + if (entityDamageEvent.getFinalDamage() >= livingEntity.getHealth()) { //This sets entity names back to whatever they are supposed to be CombatUtils.fixNames(livingEntity); } } - if(entityDamageEvent.getDamager() instanceof Arrow arrow) { + if (entityDamageEvent.getDamager() instanceof Arrow arrow) { CombatUtils.delayArrowMetaCleanup(arrow); } - if(entityDamageEvent.getEntity() instanceof Player player && entityDamageEvent.getDamager() instanceof Player) { + if (entityDamageEvent.getEntity() instanceof Player player && entityDamageEvent.getDamager() instanceof Player) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer != null) { + if (mmoPlayer.isDebugMode()) { player.sendMessage(ChatColor.GOLD + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); player.sendMessage("You are being damaged by another player in this event"); player.sendMessage("Raw Damage: " + entityDamageEvent.getDamage()); @@ -420,7 +410,7 @@ public class EntityListener implements Listener { player.sendMessage("Final damage: " + entityDamageEvent.getFinalDamage()); - if(entityDamageEvent.isCancelled()) { + if (entityDamageEvent.isCancelled()) { player.sendMessage("Event was cancelled, which means no damage should be done."); } @@ -429,10 +419,10 @@ public class EntityListener implements Listener { } } - if(entityDamageEvent.getDamager() instanceof Player player && entityDamageEvent.getEntity() instanceof Player otherPlayer) { + if (entityDamageEvent.getDamager() instanceof Player player && entityDamageEvent.getEntity() instanceof Player otherPlayer) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer != null) { + if (mmoPlayer.isDebugMode()) { player.sendMessage(ChatColor.GOLD + "(mmodebug start of combat report) EntityDamageByEntityEvent DEBUG Info:"); player.sendMessage("You are dealing damage to another player in this event"); player.sendMessage("Raw Damage: " + entityDamageEvent.getDamage()); @@ -446,7 +436,7 @@ public class EntityListener implements Listener { player.sendMessage("Target players max health: "+otherPlayer.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()); player.sendMessage("Target players current health: "+otherPlayer.getHealth()); - if(entityDamageEvent.isCancelled()) { + if (entityDamageEvent.isCancelled()) { player.sendMessage("Event was cancelled, which means no damage should be done."); } @@ -462,7 +452,7 @@ public class EntityListener implements Listener { return true; } - if(!pluginRef.isPartySystemEnabled()) { + if (!pluginRef.isPartySystemEnabled()) { return false; } @@ -471,7 +461,7 @@ public class EntityListener implements Listener { } //Party Friendly Fire - if(!mcMMO.p.getGeneralConfig().getPartyFriendlyFire()) + if (!mcMMO.p.getGeneralConfig().getPartyFriendlyFire()) if ((mcMMO.p.getPartyManager().inSameParty(defendingPlayer, attackingPlayer) || mcMMO.p.getPartyManager().areAllies(defendingPlayer, attackingPlayer)) && !(Permissions.friendlyFire(attackingPlayer) @@ -491,19 +481,17 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityDamage(EntityDamageEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity().hasMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE)) { + if (event.getEntity().hasMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE)) { event.getEntity().removeMetadata(MetadataConstants.METADATA_KEY_EXPLOSION_FROM_RUPTURE, mcMMO.p); } - if(event.getEntity() instanceof Player player) - { + if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -560,7 +548,7 @@ public class EntityListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; /* Check for invincibility */ @@ -578,12 +566,10 @@ public class EntityListener implements Listener { else if (livingEntity instanceof Tameable pet) { AnimalTamer owner = pet.getOwner(); - if(owner instanceof Player player) - { + if (owner instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } } @@ -593,8 +579,7 @@ public class EntityListener implements Listener { Wolf wolf = (Wolf) pet; //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -680,12 +665,12 @@ public class EntityListener implements Listener { public void onEntityDeath(EntityDeathEvent event) { LivingEntity entity = event.getEntity(); - if(mcMMO.getTransientEntityTracker().isTransientSummon(entity)) { + if (mcMMO.getTransientEntityTracker().isTransientSummon(entity)) { mcMMO.getTransientEntityTracker().removeSummon(entity, null, false); } /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) { return; } @@ -705,7 +690,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onCreatureSpawn(CreatureSpawnEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; LivingEntity livingEntity = event.getEntity(); @@ -730,19 +715,19 @@ public class EntityListener implements Listener { } private void trackSpawnedAndPassengers(LivingEntity livingEntity, MobMetaFlagType mobMetaFlagType) { - mobMetadataService.flagMetadata(mobMetaFlagType, livingEntity); + flagMetadata(mobMetaFlagType, livingEntity); for(Entity passenger : livingEntity.getPassengers()) { - if(passenger != null) { - mobMetadataService.flagMetadata(mobMetaFlagType, livingEntity); + if (passenger != null) { + flagMetadata(mobMetaFlagType, livingEntity); } } } @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) public void onEntityBreed(EntityBreedEvent event) { - if(ExperienceConfig.getInstance().isCOTWBreedingPrevented()) { - if(mobMetadataService.hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || mobMetadataService.hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { + if (ExperienceConfig.getInstance().isCOTWBreedingPrevented()) { + if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getFather()) || hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, event.getMother())) { event.setCancelled(true); Animals mom = (Animals) event.getMother(); Animals father = (Animals) event.getFather(); @@ -752,7 +737,7 @@ public class EntityListener implements Listener { father.setLoveModeTicks(0); //Inform the player - if(event.getBreeder() instanceof Player player) { + if (event.getBreeder() instanceof Player player) { NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.BreedingDisallowed"); } } @@ -768,7 +753,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onExplosionPrime(ExplosionPrimeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -786,15 +771,13 @@ public class EntityListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -814,7 +797,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEnitityExplode(EntityExplodeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -832,15 +815,13 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -861,7 +842,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) public void onFoodLevelChange(FoodLevelChangeEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -871,15 +852,13 @@ public class EntityListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -899,9 +878,9 @@ public class EntityListener implements Listener { //The main hand is used over the off hand if they both have food, so check the main hand first Material foodInHand; - if(mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInMainHand().getType())) { + if (mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInMainHand().getType())) { foodInHand = player.getInventory().getItemInMainHand().getType(); - } else if(mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInOffHand().getType())) { + } else if (mcMMO.getMaterialMapStore().isFood(player.getInventory().getItemInOffHand().getType())) { foodInHand = player.getInventory().getItemInOffHand().getType(); } else { return; //Not Food @@ -914,7 +893,7 @@ public class EntityListener implements Listener { */ //Hacky 1.17 support - if(foodInHand.getKey().getKey().equalsIgnoreCase("glow_berries")) { + if (foodInHand.getKey().getKey().equalsIgnoreCase("glow_berries")) { if (Permissions.isSubSkillEnabled(player, SubSkillType.HERBALISM_FARMERS_DIET)) { event.setFoodLevel(UserManager.getPlayer(player).getHerbalismManager().farmersDiet(newFoodLevel)); } @@ -985,7 +964,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onEntityTame(EntityTameEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; if (event instanceof FakeEntityTameEvent) { @@ -995,9 +974,8 @@ public class EntityListener implements Listener { Player player = (Player) event.getOwner(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -1005,16 +983,15 @@ public class EntityListener implements Listener { if (!UserManager.hasPlayerDataKey(player) || (ExperienceConfig.getInstance().isNPCInteractionPrevented() && Misc.isNPCEntityExcludingVillagers(livingEntity)) - || mobMetadataService.hasMobFlag(MobMetaFlagType.EGG_MOB, livingEntity) - || mobMetadataService.hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, livingEntity)) { + || hasMobFlag(MobMetaFlagType.EGG_MOB, livingEntity) + || hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, livingEntity)) { return; } - mobMetadataService.flagMetadata(MobMetaFlagType.PLAYER_TAMED_MOB, livingEntity); + flagMetadata(MobMetaFlagType.PLAYER_TAMED_MOB, livingEntity); //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -1030,7 +1007,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onEntityTarget(EntityTargetEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; Entity entity = event.getEntity(); @@ -1041,9 +1018,8 @@ public class EntityListener implements Listener { } /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -1069,7 +1045,7 @@ public class EntityListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPotionSplash(PotionSplashEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; ItemMeta meta = event.getPotion().getItem().getItemMeta(); @@ -1096,8 +1072,8 @@ public class EntityListener implements Listener { if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(event.getEntity() instanceof Arrow arrow) { - if(arrow.isShotFromCrossbow()) { + if (event.getEntity() instanceof Arrow arrow) { + if (arrow.isShotFromCrossbow()) { Crossbows.processCrossbows(event, pluginRef, arrow); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java index 348ba2af0..0422d1064 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java +++ b/src/main/java/com/gmail/nossr50/listeners/InteractionManager.java @@ -19,13 +19,13 @@ public class InteractionManager { public static void initMaps() { /* INIT MAPS */ - if(interactRegister == null) + if (interactRegister == null) interactRegister = new HashMap<>(); - if(subSkillList == null) + if (subSkillList == null) subSkillList = new ArrayList<>(); - if(subSkillNameMap == null) + if (subSkillNameMap == null) subSkillNameMap = new HashMap<>(); } @@ -33,10 +33,9 @@ public class InteractionManager { * Registers subskills with the Interaction registration * @param abstractSubSkill the target subskill to register */ - public static void registerSubSkill(AbstractSubSkill abstractSubSkill) - { + public static void registerSubSkill(AbstractSubSkill abstractSubSkill) { //Store a unique copy of each subskill - if(!subSkillList.contains(abstractSubSkill)) + if (!subSkillList.contains(abstractSubSkill)) subSkillList.add(abstractSubSkill); //Init ArrayList @@ -62,8 +61,7 @@ public class InteractionManager { * @param name name of subskill, not case sensitive * @return null if the subskill is not registered */ - public static AbstractSubSkill getAbstractByName(String name) - { + public static AbstractSubSkill getAbstractByName(String name) { return subSkillNameMap.get(name.toLowerCase(Locale.ENGLISH)); } @@ -73,13 +71,11 @@ public class InteractionManager { * @param plugin instance of mcMMO plugin * @param curInteractType the associated interaction type */ - public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) - { - if(interactRegister.get(curInteractType) == null) + public static void processEvent(Event event, mcMMO plugin, InteractType curInteractType) { + if (interactRegister.get(curInteractType) == null) return; - for(Interaction interaction : interactRegister.get(curInteractType)) - { + for(Interaction interaction : interactRegister.get(curInteractType)) { interaction.doInteraction(event, plugin); } } @@ -89,18 +85,15 @@ public class InteractionManager { * Interactions are extensions of abstract classes that represent modifying behaviours in Minecraft through events * @return the unique collection of all registered Interaction classes */ - public static ArrayList getSubSkillList() - { + public static ArrayList getSubSkillList() { return subSkillList; } - public static boolean hasSubSkill(String name) - { + public static boolean hasSubSkill(String name) { return getAbstractByName(name) != null; } - public static boolean hasSubSkill(SubSkillType subSkillType) - { + public static boolean hasSubSkill(SubSkillType subSkillType) { return hasSubSkill(subSkillType.getNiceNameNoSpaces(subSkillType)); } diff --git a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java index 4467ff723..116e41f0c 100644 --- a/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/InventoryListener.java @@ -9,6 +9,7 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.runnables.player.PlayerUpdateInventoryTask; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; +import com.gmail.nossr50.util.ContainerMetadataUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Permissions; @@ -41,7 +42,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceBurnEvent(FurnaceBurnEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; Block furnaceBlock = event.getBlock(); @@ -53,10 +54,10 @@ public class InventoryListener implements Listener { } Furnace furnace = (Furnace) furnaceState; - OfflinePlayer offlinePlayer = mcMMO.getSmeltingTracker().getFurnaceOwner(furnace); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(furnace); Player player; - if(offlinePlayer != null && offlinePlayer.isOnline() && offlinePlayer instanceof Player) { + if (offlinePlayer != null && offlinePlayer.isOnline() && offlinePlayer instanceof Player) { player = (Player) offlinePlayer; if (!Permissions.isSubSkillEnabled(player, SubSkillType.SMELTING_FUEL_EFFICIENCY)) { @@ -65,10 +66,10 @@ public class InventoryListener implements Listener { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer != null) { + if (mmoPlayer != null) { boolean debugMode = mmoPlayer.isDebugMode(); - if(debugMode) { + if (debugMode) { player.sendMessage("FURNACE FUEL EFFICIENCY DEBUG REPORT"); player.sendMessage("Furnace - "+furnace.hashCode()); player.sendMessage("Furnace Type: "+furnaceBlock.getType()); @@ -77,7 +78,7 @@ public class InventoryListener implements Listener { event.setBurnTime(mmoPlayer.getSmeltingManager().fuelEfficiency(event.getBurnTime())); - if(debugMode) { + if (debugMode) { player.sendMessage("New Furnace Burn Length (after applying fuel efficiency) "+event.getBurnTime()); player.sendMessage(""); } @@ -88,7 +89,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceSmeltEvent(FurnaceSmeltEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; BlockState blockState = event.getBlock().getState(); //Furnaces can only be cast from a BlockState not a Block @@ -98,15 +99,15 @@ public class InventoryListener implements Listener { return; } - if(blockState instanceof Furnace furnace) { - OfflinePlayer offlinePlayer = mcMMO.getSmeltingTracker().getFurnaceOwner(furnace); + if (blockState instanceof Furnace furnace) { + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(furnace); - if(offlinePlayer != null) { + if (offlinePlayer != null) { McMMOPlayer offlineProfile = UserManager.getOfflinePlayer(offlinePlayer); //Profile doesn't exist - if(offlineProfile != null) { + if (offlineProfile != null) { //Process smelting offlineProfile.getSmeltingManager().smeltProcessing(event, furnace); } @@ -117,7 +118,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onFurnaceExtractEvent(FurnaceExtractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; BlockState furnaceBlock = event.getBlock().getState(); @@ -128,11 +129,10 @@ public class InventoryListener implements Listener { Player player = event.getPlayer(); - if(furnaceBlock instanceof Furnace) { + if (furnaceBlock instanceof Furnace) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -141,8 +141,7 @@ public class InventoryListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -155,26 +154,26 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryClickEventNormal(InventoryClickEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; //We should never care to do processing if the player clicks outside the window -// if(isOutsideWindowClick(event)) +// if (isOutsideWindowClick(event)) // return; Inventory inventory = event.getInventory(); Player player = ((Player) event.getWhoClicked()).getPlayer(); + McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(event.getInventory() instanceof FurnaceInventory) - { - Furnace furnace = mcMMO.getSmeltingTracker().getFurnaceFromInventory(event.getInventory()); + if (event.getInventory() instanceof FurnaceInventory furnaceInventory) { + //Switch owners + ContainerMetadataUtils.processContainerOwnership(furnaceInventory.getHolder(), player); + } - if (furnace != null) - { - //Switch owners - mcMMO.getSmeltingTracker().processFurnaceOwnership(furnace, player); - } + if (event.getInventory() instanceof BrewerInventory brewerInventory) { + // switch owners + ContainerMetadataUtils.processContainerOwnership(brewerInventory.getHolder(), player); } if (!(inventory instanceof BrewerInventory)) { @@ -189,22 +188,27 @@ public class InventoryListener implements Listener { HumanEntity whoClicked = event.getWhoClicked(); - if (!UserManager.hasPlayerDataKey(event.getWhoClicked()) || !Permissions.isSubSkillEnabled(whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { + if (mmoPlayer == null || !Permissions.isSubSkillEnabled(whoClicked, SubSkillType.ALCHEMY_CONCOCTIONS)) { return; } + // TODO: Investigate why this WG check is all the way down here? /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - ItemStack clicked = event.getCurrentItem(); - ItemStack cursor = event.getCursor(); + final ItemStack clicked = event.getCurrentItem(); + final ItemStack cursor = event.getCursor(); - if ((clicked != null && (clicked.getType() == Material.POTION || clicked.getType() == Material.SPLASH_POTION || clicked.getType() == Material.LINGERING_POTION)) || (cursor != null && (cursor.getType() == Material.POTION || cursor.getType() == Material.SPLASH_POTION || cursor.getType() == Material.LINGERING_POTION))) { - AlchemyPotionBrewer.scheduleCheck(player, stand); + if ((clicked != null && (clicked.getType() == Material.POTION + || clicked.getType() == Material.SPLASH_POTION + || clicked.getType() == Material.LINGERING_POTION)) + || (cursor != null && (cursor.getType() == Material.POTION + || cursor.getType() == Material.SPLASH_POTION + || cursor.getType() == Material.LINGERING_POTION))) { + AlchemyPotionBrewer.scheduleCheck(stand); return; } @@ -214,11 +218,11 @@ public class InventoryListener implements Listener { if (click.isShiftClick()) { switch (slot) { case FUEL: - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); return; case CONTAINER: case QUICKBAR: - if (!AlchemyPotionBrewer.isValidIngredient(player, clicked)) { + if (!AlchemyPotionBrewer.isValidIngredientByPlayer(player, clicked)) { return; } @@ -228,24 +232,22 @@ public class InventoryListener implements Listener { event.setCancelled(true); AlchemyPotionBrewer.scheduleUpdate(inventory); - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); return; default: } - } - else if (slot == InventoryType.SlotType.FUEL) { + } else if (slot == InventoryType.SlotType.FUEL) { boolean emptyClicked = AlchemyPotionBrewer.isEmpty(clicked); if (AlchemyPotionBrewer.isEmpty(cursor)) { if (emptyClicked && click == ClickType.NUMBER_KEY) { - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); return; } - AlchemyPotionBrewer.scheduleCheck(player, stand); - } - else if (emptyClicked) { - if (AlchemyPotionBrewer.isValidIngredient(player, cursor)) { + AlchemyPotionBrewer.scheduleCheck(stand); + } else if (emptyClicked) { + if (AlchemyPotionBrewer.isValidIngredientByPlayer(player, cursor)) { int amount = cursor.getAmount(); if (click == ClickType.LEFT || (click == ClickType.RIGHT && amount == 1)) { @@ -254,9 +256,8 @@ public class InventoryListener implements Listener { event.setCursor(null); AlchemyPotionBrewer.scheduleUpdate(inventory); - AlchemyPotionBrewer.scheduleCheck(player, stand); - } - else if (click == ClickType.RIGHT) { + AlchemyPotionBrewer.scheduleCheck(stand); + } else if (click == ClickType.RIGHT) { event.setCancelled(true); ItemStack one = cursor.clone(); @@ -269,7 +270,7 @@ public class InventoryListener implements Listener { event.setCursor(rest); AlchemyPotionBrewer.scheduleUpdate(inventory); - AlchemyPotionBrewer.scheduleCheck(player, stand); + AlchemyPotionBrewer.scheduleCheck(stand); } } } @@ -284,7 +285,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryDragEvent(InventoryDragEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; Inventory inventory = event.getInventory(); @@ -316,15 +317,14 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if (AlchemyPotionBrewer.isValidIngredient(player, cursor)) { + if (AlchemyPotionBrewer.isValidIngredientByPlayer(player, cursor)) { // Not handled: dragging custom ingredients over ingredient slot (does not trigger any event) - AlchemyPotionBrewer.scheduleCheck(player, (BrewingStand) holder); + AlchemyPotionBrewer.scheduleCheck((BrewingStand) holder); return; } @@ -335,14 +335,14 @@ public class InventoryListener implements Listener { // Apparently sometimes vanilla brewing beats our task listener to the actual brew. We handle this by cancelling the vanilla event and finishing our brew ourselves. @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) - public void onBrew(BrewEvent event) - { + public void onBrew(BrewEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) return; if (event instanceof FakeBrewEvent) return; + Location location = event.getBlock().getLocation(); if (Alchemy.brewingStandMap.containsKey(location)) { Alchemy.brewingStandMap.get(location).finishImmediately(); @@ -350,58 +350,77 @@ public class InventoryListener implements Listener { } } +// @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) +// public void onBrewStart(BrewingStartEvent event) { +// /* WORLD BLACKLIST CHECK */ +// if (WorldBlacklist.isWorldBlacklisted(event.getBlock().getWorld())) +// return; +// +// if (event instanceof FakeEvent) +// return; +// } + @EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) public void onInventoryMoveItemEvent(InventoryMoveItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(event.getSource().getLocation() != null) - if(WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) + if (event.getSource().getLocation() != null) + if (WorldBlacklist.isWorldBlacklisted(event.getSource().getLocation().getWorld())) return; - Inventory inventory = event.getDestination(); + final Inventory inventory = event.getDestination(); if (!(inventory instanceof BrewerInventory)) { return; } - InventoryHolder holder = inventory.getHolder(); + final InventoryHolder holder = inventory.getHolder(); - if (!(holder instanceof BrewingStand)) { - return; - } + if (holder instanceof BrewingStand brewingStand) { - ItemStack item = event.getItem(); + ItemStack item = event.getItem(); - if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) { - event.setCancelled(true); - return; - } + if (mcMMO.p.getGeneralConfig().getPreventHopperTransferIngredients() && item.getType() != Material.POTION && item.getType() != Material.SPLASH_POTION && item.getType() != Material.LINGERING_POTION) { + event.setCancelled(true); + return; + } - if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) { - event.setCancelled(true); - return; - } + if (mcMMO.p.getGeneralConfig().getPreventHopperTransferBottles() && (item.getType() == Material.POTION || item.getType() == Material.SPLASH_POTION || item.getType() == Material.LINGERING_POTION)) { + event.setCancelled(true); + return; + } + int ingredientLevel = 1; - if (mcMMO.p.getGeneralConfig().getEnabledForHoppers() && AlchemyPotionBrewer.isValidIngredient(null, item)) { - AlchemyPotionBrewer.scheduleCheck(null, (BrewingStand) holder); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); + if (offlinePlayer != null && offlinePlayer.isOnline()) { + McMMOPlayer mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + if (mmoPlayer != null) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + } + } + + if (mcMMO.p.getGeneralConfig().getEnabledForHoppers() + && AlchemyPotionBrewer.isValidIngredientByLevel(ingredientLevel, item)) { + AlchemyPotionBrewer.scheduleCheck(brewingStand); + } } } @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onInventoryClickEvent(InventoryClickEvent event) { - if(event.getCurrentItem() == null) { + if (event.getCurrentItem() == null) { return; } SkillUtils.removeAbilityBuff(event.getCurrentItem()); if (event.getAction() == InventoryAction.HOTBAR_SWAP) { - if(isOutsideWindowClick(event)) + if (isOutsideWindowClick(event)) return; PlayerInventory playerInventory = event.getWhoClicked().getInventory(); - if(playerInventory.getItem(event.getHotbarButton()) != null) + if (playerInventory.getItem(event.getHotbarButton()) != null) SkillUtils.removeAbilityBuff(playerInventory.getItem(event.getHotbarButton())); } } @@ -414,7 +433,7 @@ public class InventoryListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onCraftItem(CraftItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWhoClicked().getWorld())) return; final HumanEntity whoClicked = event.getWhoClicked(); @@ -433,9 +452,8 @@ public class InventoryListener implements Listener { Player player = (Player) whoClicked; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } diff --git a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java index ab1526382..74f262289 100644 --- a/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/PlayerListener.java @@ -71,13 +71,13 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerTeleport(PlayerTeleportEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) { + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) { //Remove scoreboards - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { ScoreboardManager.teardownPlayer(event.getPlayer()); } return; - } else if(WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { + } else if (WorldBlacklist.isWorldBlacklisted(event.getFrom().getWorld()) && mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) { //This only fires if they are travelling to a non-blacklisted world from a blacklisted world //Setup scoreboards @@ -87,9 +87,8 @@ public class PlayerListener implements Listener { Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -98,8 +97,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -164,7 +162,7 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDeathMonitor(PlayerDeathEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; boolean statLossEnabled = HardcoreManager.isStatLossEnabled(); @@ -183,9 +181,8 @@ public class PlayerListener implements Listener { Player killer = killedPlayer.getKiller(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(killedPlayer)) return; } @@ -227,8 +224,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -250,13 +246,12 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerDropItem(PlayerDropItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(event.getPlayer())) return; } @@ -281,15 +276,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onPlayerFishHighest(PlayerFishEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -298,8 +292,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -308,7 +301,7 @@ public class PlayerListener implements Listener { switch (event.getState()) { case CAUGHT_FISH: //TODO Update to new API once available! Waiting for case CAUGHT_TREASURE - if(event.getCaught() != null) { + if (event.getCaught() != null) { Item fishingCatch = (Item) event.getCaught(); if (mcMMO.p.getGeneralConfig().getFishingOverrideTreasures() && @@ -329,7 +322,7 @@ public class PlayerListener implements Listener { if (Permissions.vanillaXpBoost(player, PrimarySkillType.FISHING)) { //Don't modify XP below vanilla values - if(fishingManager.handleVanillaXpBoost(event.getExpToDrop()) > 1) + if (fishingManager.handleVanillaXpBoost(event.getExpToDrop()) > 1) event.setExpToDrop(fishingManager.handleVanillaXpBoost(event.getExpToDrop())); } } @@ -367,15 +360,14 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onPlayerFishMonitor(PlayerFishEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -384,8 +376,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -393,20 +384,16 @@ public class PlayerListener implements Listener { FishingManager fishingManager = UserManager.getPlayer(player).getFishingManager(); //Track the hook - if(ExperienceConfig.getInstance().isFishingExploitingPrevented()) - { - if(event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) - { + if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { + if (event.getHook().getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() == 0) { fishingManager.setFishHookReference(event.getHook()); } //Spam Fishing - if(event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) - { + if (event.getState() == PlayerFishEvent.State.CAUGHT_FISH && fishingManager.isFishingTooOften()) { event.setExpToDrop(0); - if(caught instanceof Item caughtItem) - { + if (caught instanceof Item caughtItem) { caughtItem.remove(); } @@ -421,19 +408,19 @@ public class PlayerListener implements Listener { ItemStack inHand = player.getInventory().getItemInMainHand(); //Grab lure level - if(inHand != null + if (inHand != null && inHand.getItemMeta() != null && inHand.getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { - if(inHand.getItemMeta().hasEnchants()) { + if (inHand.getItemMeta().hasEnchants()) { for(Enchantment enchantment : inHand.getItemMeta().getEnchants().keySet()) { - if(enchantment.toString().toLowerCase().contains("lure")) { + if (enchantment.toString().toLowerCase().contains("lure")) { lureLevel = inHand.getEnchantmentLevel(enchantment); } } } // Prevent any potential odd behavior by only processing if no offhand fishing rod is present - if(!player.getInventory().getItemInOffHand().getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { + if (!player.getInventory().getItemInOffHand().getType().getKey().getKey().equalsIgnoreCase("fishing_rod")) { // In case of offhand fishing rod, don't process anything fishingManager.masterAngler(event.getHook(), lureLevel); fishingManager.setFishingTarget(); @@ -442,8 +429,8 @@ public class PlayerListener implements Listener { } return; case CAUGHT_FISH: - if(caught instanceof Item) { - if(ExperienceConfig.getInstance().isFishingExploitingPrevented()) { + if (caught instanceof Item) { + if (ExperienceConfig.getInstance().isFishingExploitingPrevented()) { fishingManager.processExploiting(event.getHook().getLocation().toVector()); @@ -482,20 +469,18 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerPickupItem(EntityPickupItemEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getEntity().getWorld())) return; - if(Misc.isNPCEntityExcludingVillagers(event.getEntity())) { + if (Misc.isNPCEntityExcludingVillagers(event.getEntity())) { return; } - if(event.getEntity() instanceof Player player) - { + if (event.getEntity() instanceof Player player) { /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } @@ -505,7 +490,7 @@ public class PlayerListener implements Listener { //Profile not loaded McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -513,7 +498,7 @@ public class PlayerListener implements Listener { ItemStack dropStack = drop.getItemStack(); //Remove tracking - if(drop.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { + if (drop.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { drop.removeMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, mcMMO.p); } @@ -566,7 +551,7 @@ public class PlayerListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Profile not loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -618,8 +603,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -634,28 +618,27 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) public void onPlayerInteractLowest(PlayerInteractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if(event.getClickedBlock() == null) + if (event.getClickedBlock() == null) return; Block clickedBlock = event.getClickedBlock(); Material clickedBlockType = clickedBlock.getType(); //The blacklist contains interactable blocks so its a convenient filter - if(clickedBlockType == Repair.anvilMaterial || clickedBlockType == Salvage.anvilMaterial) { + if (clickedBlockType == Repair.anvilMaterial || clickedBlockType == Salvage.anvilMaterial) { event.setUseItemInHand(Event.Result.ALLOW); - if(!event.getPlayer().isSneaking() && mcMMO.getMaterialMapStore().isToolActivationBlackListed(clickedBlockType)) { + if (!event.getPlayer().isSneaking() && mcMMO.getMaterialMapStore().isToolActivationBlackListed(clickedBlockType)) { event.setUseInteractedBlock(Event.Result.DENY); } } @@ -665,8 +648,7 @@ public class PlayerListener implements Listener { } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -715,8 +697,7 @@ public class PlayerListener implements Listener { else if (miningManager.canDetonate()) { if (type == Material.TNT) { event.setCancelled(true); // Don't detonate the TNT if they're too close - } - else { + } else { miningManager.remoteDetonation(); } } @@ -764,25 +745,25 @@ public class PlayerListener implements Listener { @EventHandler(priority = EventPriority.MONITOR) public void onPlayerInteractMonitor(PlayerInteractEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getPlayer().getWorld())) return; Player player = event.getPlayer(); /* WORLD GUARD MAIN FLAG CHECK */ - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasMainFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasMainFlag(player)) return; } - if (event.getHand() != EquipmentSlot.HAND || !UserManager.hasPlayerDataKey(player) || player.getGameMode() == GameMode.CREATIVE) { + if (event.getHand() != EquipmentSlot.HAND + || !UserManager.hasPlayerDataKey(player) + || player.getGameMode() == GameMode.CREATIVE) { return; } //Profile not loaded - if(UserManager.getPlayer(player) == null) - { + if (UserManager.getPlayer(player) == null) { return; } @@ -793,13 +774,10 @@ public class PlayerListener implements Listener { ItemStack heldItem = player.getInventory().getItemInMainHand(); //Spam Fishing Detection - if(event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) - { - if(ExperienceConfig.getInstance().isFishingExploitingPrevented() - && (heldItem.getType() == Material.FISHING_ROD || player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD)) - { - if(player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) - { + if (event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.RIGHT_CLICK_AIR) { + if (ExperienceConfig.getInstance().isFishingExploitingPrevented() + && (heldItem.getType() == Material.FISHING_ROD || player.getInventory().getItemInOffHand().getType() == Material.FISHING_ROD)) { + if (player.isInsideVehicle() && (player.getVehicle() instanceof Minecart || player.getVehicle() instanceof PoweredMinecart)) { player.getVehicle().eject(); } @@ -809,12 +787,12 @@ public class PlayerListener implements Listener { switch (event.getAction()) { case RIGHT_CLICK_BLOCK: - if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { + if (player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { break; } //Hmm - if(event.getClickedBlock() == null) + if (event.getClickedBlock() == null) return; Block block = event.getClickedBlock(); @@ -841,7 +819,7 @@ public class PlayerListener implements Listener { HerbalismManager herbalismManager = mcMMOPlayer.getHerbalismManager(); // FakePlayerAnimationEvent fakeSwing = new FakePlayerAnimationEvent(event.getPlayer(), PlayerAnimationType.ARM_SWING); //PlayerAnimationEvent compat - if(!event.isCancelled() || event.useInteractedBlock() != Event.Result.DENY) { + if (!event.isCancelled() || event.useInteractedBlock() != Event.Result.DENY) { //TODO: Is this code to set false from bone meal even needed? I'll have to double check later. if (heldItem.getType() == Material.BONE_MEAL) { switch (blockState.getType().toString()) { @@ -852,14 +830,14 @@ public class PlayerListener implements Listener { case "NETHER_WART_BLOCK": case "POTATO": case "MANGROVE_PROPAGULE": - mcMMO.getPlaceStore().setFalse(blockState); + mcMMO.getUserBlockTracker().setEligible(blockState); break; } } if (herbalismManager.canGreenThumbBlock(blockState)) { //call event for Green Thumb Block - if(!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, block).isCancelled()) { + if (!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, block).isCancelled()) { // Bukkit.getPluginManager().callEvent(fakeSwing); player.getInventory().getItemInMainHand().setAmount(heldItem.getAmount() - 1); player.updateInventory(); @@ -870,7 +848,7 @@ public class PlayerListener implements Listener { } /* SHROOM THUMB CHECK */ else if (herbalismManager.canUseShroomThumb(blockState)) { - if(!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_SHROOM_THUMB, block).isCancelled()) { + if (!EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_SHROOM_THUMB, block).isCancelled()) { // Bukkit.getPluginManager().callEvent(fakeSwing); event.setCancelled(true); if (herbalismManager.processShroomThumb(blockState) @@ -885,7 +863,7 @@ public class PlayerListener implements Listener { break; case RIGHT_CLICK_AIR: - if(player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { + if (player.getInventory().getItemInOffHand().getType() != Material.AIR && !player.isInsideVehicle() && !player.isSneaking()) { break; } @@ -924,11 +902,9 @@ public class PlayerListener implements Listener { if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.WOLF.getConfigEntityTypeEntry())) { tamingManager.summonWolf(); - } - else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { + } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry())) { tamingManager.summonOcelot(); - } - else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { + } else if (type == mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.HORSE.getConfigEntityTypeEntry())) { tamingManager.summonHorse(); } @@ -960,9 +936,9 @@ public class PlayerListener implements Listener { return; } - if(plugin.getChatManager().isChatChannelEnabled(mcMMOPlayer.getChatChannel())) { - if(mcMMOPlayer.getChatChannel() != ChatChannel.NONE) { - if(plugin.getChatManager().isMessageAllowed(mcMMOPlayer)) { + if (plugin.getChatManager().isChatChannelEnabled(mcMMOPlayer.getChatChannel())) { + if (mcMMOPlayer.getChatChannel() != ChatChannel.NONE) { + if (plugin.getChatManager().isMessageAllowed(mcMMOPlayer)) { //If the message is allowed we cancel this event to avoid double sending messages plugin.getChatManager().processPlayerMessage(mcMMOPlayer, event.getMessage(), event.isAsynchronous()); event.setCancelled(true); @@ -1028,8 +1004,7 @@ public class PlayerListener implements Listener { if (event.getHand() == EquipmentSlot.OFF_HAND) { itemInHand = event.getPlayer().getInventory().getItemInOffHand(); - } - else { + } else { itemInHand = event.getPlayer().getInventory().getItemInMainHand(); } diff --git a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java index 0fe8eec9f..3d5bb1e0e 100644 --- a/src/main/java/com/gmail/nossr50/listeners/SelfListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/SelfListener.java @@ -24,8 +24,7 @@ public class SelfListener implements Listener { //Used in task scheduling and other things private final mcMMO plugin; - public SelfListener(mcMMO plugin) - { + public SelfListener(mcMMO plugin) { this.plugin = plugin; } @@ -37,13 +36,12 @@ public class SelfListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //TODO: Handle proper validation at the event level - if(mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) + if (mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) return; - if(player.isOnline()) { + if (player.isOnline()) { //Players can gain multiple levels especially during xprate events - for(int i = 0; i < event.getLevelsGained(); i++) - { + for(int i = 0; i < event.getLevelsGained(); i++) { int previousLevelGained = event.getSkillLevel() - i; //Send player skill unlock notifications UserManager.getPlayer(player).processUnlockNotifications(plugin, event.getSkill(), previousLevelGained); @@ -52,7 +50,7 @@ public class SelfListener implements Listener { //Reset the delay timer RankUtils.resetUnlockDelayTimer(); - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.handleLevelUp(player, skill); } } @@ -61,8 +59,8 @@ public class SelfListener implements Listener { public void onPlayerXp(McMMOPlayerXpGainEvent event) { Player player = event.getPlayer(); - if(player.isOnline()) { - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (player.isOnline()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.handleXp(player, event.getSkill()); } } @@ -70,8 +68,8 @@ public class SelfListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onAbility(McMMOPlayerAbilityActivateEvent event) { Player player = event.getPlayer(); - if(player.isOnline()) { - if(mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) + if (player.isOnline()) { + if (mcMMO.p.getGeneralConfig().getScoreboardsEnabled()) ScoreboardManager.cooldownUpdate(event.getPlayer(), event.getSkill()); } } @@ -82,49 +80,43 @@ public class SelfListener implements Listener { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //TODO: Handle proper validation at the event level - if(mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) + if (mcMMOPlayer == null || !mcMMOPlayer.getProfile().isLoaded()) return; PrimarySkillType primarySkillType = event.getSkill(); - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage(event.getSkill().toString() + " XP Gained"); mcMMOPlayer.getPlayer().sendMessage("Incoming Raw XP: "+event.getRawXpGained()); } //WorldGuard XP Check - if(event.getXpGainReason() == XPGainReason.PVE || + if (event.getXpGainReason() == XPGainReason.PVE || event.getXpGainReason() == XPGainReason.PVP || event.getXpGainReason() == XPGainReason.SHARED_PVE || - event.getXpGainReason() == XPGainReason.SHARED_PVP) - { - if(WorldGuardUtils.isWorldGuardLoaded()) - { - if(!WorldGuardManager.getInstance().hasXPFlag(player)) - { + event.getXpGainReason() == XPGainReason.SHARED_PVP) { + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasXPFlag(player)) { event.setRawXpGained(0); event.setCancelled(true); - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage("No WG XP Flag - New Raw XP: "+event.getRawXpGained()); } } } } - if (event.getXpGainReason() == XPGainReason.COMMAND) - { + if (event.getXpGainReason() == XPGainReason.COMMAND) { return; } - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled()) - { + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled()) { int earlyGameBonusXP = 0; //Give some bonus XP for low levels - if(PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) - { + if (PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { earlyGameBonusXP += (mcMMOPlayer.getXpToLevel(primarySkillType) * 0.05); event.setRawXpGained(event.getRawXpGained() + earlyGameBonusXP); } @@ -133,7 +125,7 @@ public class SelfListener implements Listener { int threshold = ExperienceConfig.getInstance().getDiminishedReturnsThreshold(primarySkillType); if (threshold <= 0 || !ExperienceConfig.getInstance().getDiminishedReturnsEnabled()) { - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage("Final Raw XP: "+event.getRawXpGained()); } // Diminished returns is turned off @@ -167,12 +159,10 @@ public class SelfListener implements Listener { * Make sure players get a guaranteed minimum of XP */ //If there is no guaranteed minimum proceed, otherwise only proceed if newValue would be higher than our guaranteed minimum - if(guaranteedMinimum <= 0 || newValue > guaranteedMinimum) - { + if (guaranteedMinimum <= 0 || newValue > guaranteedMinimum) { if (newValue > 0) { event.setRawXpGained(newValue); - } - else { + } else { event.setCancelled(true); } } else { @@ -181,7 +171,7 @@ public class SelfListener implements Listener { } - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { mcMMOPlayer.getPlayer().sendMessage("Final Raw XP: "+event.getRawXpGained()); } } diff --git a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java index 4c24930c6..54fa2a379 100644 --- a/src/main/java/com/gmail/nossr50/listeners/WorldListener.java +++ b/src/main/java/com/gmail/nossr50/listeners/WorldListener.java @@ -26,13 +26,13 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onStructureGrow(StructureGrowEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; // Using 50 ms later as I do not know of a way to run one tick later (safely) plugin.getFoliaLib().getImpl().runLater(() -> { for (BlockState blockState : event.getBlocks()) { - mcMMO.getPlaceStore().setFalse(blockState); + mcMMO.getUserBlockTracker().setEligible(blockState); } }, 1); } @@ -45,10 +45,10 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onWorldUnload(WorldUnloadEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; - mcMMO.getPlaceStore().unloadWorld(event.getWorld()); + mcMMO.getChunkManager().unloadWorld(event.getWorld()); } /** @@ -59,11 +59,11 @@ public class WorldListener implements Listener { @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { /* WORLD BLACKLIST CHECK */ - if(WorldBlacklist.isWorldBlacklisted(event.getWorld())) + if (WorldBlacklist.isWorldBlacklisted(event.getWorld())) return; Chunk chunk = event.getChunk(); - mcMMO.getPlaceStore().chunkUnloaded(chunk.getX(), chunk.getZ(), event.getWorld()); + mcMMO.getChunkManager().chunkUnloaded(chunk.getX(), chunk.getZ(), event.getWorld()); } } diff --git a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java index e6a37d924..81ab06625 100644 --- a/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java +++ b/src/main/java/com/gmail/nossr50/locale/LocaleLoader.java @@ -380,7 +380,7 @@ public final class LocaleLoader { * @return The message with the hex color codes translated to Minecraft color codes */ public static String translateHexColorCodes(String messageWithHex) { - if(messageWithHex == null) { + if (messageWithHex == null) { return null; } diff --git a/src/main/java/com/gmail/nossr50/mcMMO.java b/src/main/java/com/gmail/nossr50/mcMMO.java index a8c1c8601..3f23597ba 100644 --- a/src/main/java/com/gmail/nossr50/mcMMO.java +++ b/src/main/java/com/gmail/nossr50/mcMMO.java @@ -19,7 +19,6 @@ import com.gmail.nossr50.database.DatabaseManagerFactory; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.subskills.acrobatics.Roll; import com.gmail.nossr50.listeners.*; -import com.gmail.nossr50.metadata.MetadataService; import com.gmail.nossr50.party.PartyManager; import com.gmail.nossr50.placeholders.PapiExpansion; import com.gmail.nossr50.runnables.SaveTimerTask; @@ -40,6 +39,7 @@ import com.gmail.nossr50.skills.salvage.salvageables.SimpleSalvageableManager; import com.gmail.nossr50.util.*; import com.gmail.nossr50.util.blockmeta.ChunkManager; import com.gmail.nossr50.util.blockmeta.ChunkManagerFactory; +import com.gmail.nossr50.util.blockmeta.UserBlockTracker; import com.gmail.nossr50.util.commands.CommandRegistrationManager; import com.gmail.nossr50.util.compat.CompatibilityManager; import com.gmail.nossr50.util.experience.FormulaManager; @@ -50,7 +50,6 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillTools; -import com.gmail.nossr50.util.skills.SmeltingTracker; import com.gmail.nossr50.util.upgrade.UpgradeManager; import com.gmail.nossr50.worldguard.WorldGuardManager; import com.tcoded.folialib.FoliaLib; @@ -78,21 +77,17 @@ import java.util.ArrayList; import java.util.List; public class mcMMO extends JavaPlugin { - - /* Managers & Services */ private static PlatformManager platformManager; - private static MetadataService metadataService; - private static ChunkManager placeStore; - private static RepairableManager repairableManager; + private static ChunkManager chunkManager; + private static RepairableManager repairableManager; private static SalvageableManager salvageableManager; - private static ModManager modManager; - private static DatabaseManager databaseManager; - private static FormulaManager formulaManager; - private static UpgradeManager upgradeManager; + private static ModManager modManager; + private static DatabaseManager databaseManager; + private static FormulaManager formulaManager; + private static UpgradeManager upgradeManager; private static MaterialMapStore materialMapStore; private static PlayerLevelUtils playerLevelUtils; - private static SmeltingTracker smeltingTracker; private static TransientMetadataTools transientMetadataTools; private static ChatManager chatManager; private static CommandManager commandManager; //ACF @@ -140,28 +135,20 @@ public class mcMMO extends JavaPlugin { private GeneralConfig generalConfig; private AdvancedConfig advancedConfig; private PartyConfig partyConfig; + private PotionConfig potionConfig; private CustomItemSupportConfig customItemSupportConfig; + private EnchantmentMapper enchantmentMapper; + private AttributeMapper attributeMapper; private FoliaLib foliaLib; private PartyManager partyManager; -// private RepairConfig repairConfig; -// private SalvageConfig salvageConfig; -// private PersistentDataConfig persistentDataConfig; -// private ChatConfig chatConfig; -// private CoreSkillsConfig coreSkillsConfig; -// private RankConfig rankConfig; -// private TreasureConfig treasureConfig; -// private FishingTreasureConfig fishingTreasureConfig; -// private SoundConfig soundConfig; - public mcMMO() { p = this; } - protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) - { + protected mcMMO(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) { super(loader, description, dataFolder, file); } @@ -194,9 +181,6 @@ public class mcMMO extends JavaPlugin { //Platform Manager platformManager = new PlatformManager(); - //metadata service - metadataService = new MetadataService(this); - MetadataConstants.MCMMO_METADATA_VALUE = new FixedMetadataValue(this, true); PluginManager pluginManager = getServer().getPluginManager(); @@ -207,8 +191,11 @@ public class mcMMO extends JavaPlugin { modManager = new ModManager(); - //Init Material Maps + // Init Material Maps materialMapStore = new MaterialMapStore(); + // Init compatibility mappers + enchantmentMapper = new EnchantmentMapper(this); + attributeMapper = new AttributeMapper(this); loadConfigFiles(); @@ -220,7 +207,7 @@ public class mcMMO extends JavaPlugin { checkModConfigs(); } - if(projectKorraEnabled) { + if (projectKorraEnabled) { getLogger().info("ProjectKorra was detected, this can cause some issues with weakness potions and combat skills for mcMMO"); } @@ -241,8 +228,7 @@ public class mcMMO extends JavaPlugin { //Check for the newer API and tell them what to do if its missing checkForOutdatedAPI(); - if(serverAPIOutdated) - { + if (serverAPIOutdated) { foliaLib .getImpl() .runTimer( @@ -250,8 +236,7 @@ public class mcMMO extends JavaPlugin { 20, 20*60*30 ); - if(platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) - { + if (platformManager.getServerSoftware() == ServerSoftwareType.CRAFT_BUKKIT) { foliaLib .getImpl() .runTimer( @@ -280,7 +265,7 @@ public class mcMMO extends JavaPlugin { scheduleTasks(); CommandRegistrationManager.registerCommands(); - placeStore = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager + chunkManager = ChunkManagerFactory.getChunkManager(); // Get our ChunkletManager if (generalConfig.getPTPCommandWorldPermissions()) { Permissions.generateWorldTeleportPermissions(); @@ -293,11 +278,11 @@ public class mcMMO extends JavaPlugin { //If anonymous statistics are enabled then use them Metrics metrics; - if(generalConfig.getIsMetricsEnabled()) { + if (generalConfig.getIsMetricsEnabled()) { metrics = new Metrics(this, 3894); metrics.addCustomChart(new SimplePie("version", () -> getDescription().getVersion())); - if(generalConfig.getIsRetroMode()) + if (generalConfig.getIsRetroMode()) metrics.addCustomChart(new SimplePie("leveling_system", () -> "Retro")); else metrics.addCustomChart(new SimplePie("leveling_system", () -> "Standard")); @@ -307,8 +292,7 @@ public class mcMMO extends JavaPlugin { if (!(t instanceof ExceptionInInitializerError)) { t.printStackTrace(); - } - else { + } else { getLogger().info("Please do not replace the mcMMO jar while the server is running."); } @@ -324,9 +308,6 @@ public class mcMMO extends JavaPlugin { //Init the blacklist worldBlacklist = new WorldBlacklist(this); - //Init smelting tracker - smeltingTracker = new SmeltingTracker(); - //Set up Adventure's audiences audiences = BukkitAudiences.create(this); @@ -339,7 +320,7 @@ public class mcMMO extends JavaPlugin { transientEntityTracker = new TransientEntityTracker(); setServerShutdown(false); //Reset flag, used to make decisions about async saves - if(Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { new PapiExpansion().register(); } } @@ -365,11 +346,13 @@ public class mcMMO extends JavaPlugin { } @Override - public void onLoad() - { - if(getServer().getPluginManager().getPlugin("WorldGuard") != null) { + public void onLoad() { + if (getServer().getPluginManager().getPlugin("WorldGuard") != null) { WorldGuardManager.getInstance().registerFlags(); } + + // ProtocolLib + // protocolLibManager = new ProtocolLibManager(this); } /** @@ -385,15 +368,15 @@ public class mcMMO extends JavaPlugin { UserManager.saveAll(); // Make sure to save player information if the server shuts down UserManager.clearAll(); Alchemy.finishAllBrews(); // Finish all partially complete AlchemyBrewTasks to prevent vanilla brewing continuation on restart - if(partyConfig.isPartyEnabled()) + if (partyConfig.isPartyEnabled()) getPartyManager().saveParties(); // Save our parties //TODO: Needed? - if(generalConfig.getScoreboardsEnabled()) + if (generalConfig.getScoreboardsEnabled()) ScoreboardManager.teardownAll(); formulaManager.saveFormula(); - placeStore.closeAll(); + chunkManager.closeAll(); } catch (Exception e) { e.printStackTrace(); @@ -456,8 +439,30 @@ public class mcMMO extends JavaPlugin { return formulaManager; } + /** + * Get the {@link UserBlockTracker}. + * @return the {@link UserBlockTracker} + */ + public static UserBlockTracker getUserBlockTracker() { + return chunkManager; + } + + /** + * Get the chunk manager. + * @return the chunk manager + */ + public static ChunkManager getChunkManager() { + return chunkManager; + } + + /** + * Get the chunk manager. + * @deprecated Use {@link #getChunkManager()} or {@link #getUserBlockTracker()} instead. + * @return the chunk manager + */ + @Deprecated(since = "2.2.013", forRemoval = true) public static ChunkManager getPlaceStore() { - return placeStore; + return chunkManager; } public static RepairableManager getRepairableManager() { @@ -484,10 +489,6 @@ public class mcMMO extends JavaPlugin { return platformManager.getCompatibilityManager(); } - public static MetadataService getMetadataService() { - return metadataService; - } - @Deprecated public static void setDatabaseManager(DatabaseManager databaseManager) { mcMMO.databaseManager = databaseManager; @@ -567,7 +568,11 @@ public class mcMMO extends JavaPlugin { FishingTreasureConfig.getInstance(); HiddenConfig.getInstance(); mcMMO.p.getAdvancedConfig(); - PotionConfig.getInstance(); + + // init potion config + potionConfig = new PotionConfig(); + potionConfig.loadPotions(); + CoreSkillsConfig.getInstance(); SoundConfig.getInstance(); RankConfig.getInstance(); @@ -628,8 +633,7 @@ public class mcMMO extends JavaPlugin { InteractionManager.initMaps(); //Init maps - if(CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) - { + if (CoreSkillsConfig.getInstance().isPrimarySkillEnabled(PrimarySkillType.ACROBATICS)) { LogUtils.debug(mcMMO.p.getLogger(), "Enabling Acrobatics Skills"); //TODO: Should do this differently @@ -664,13 +668,12 @@ public class mcMMO extends JavaPlugin { if (purgeIntervalTicks == 0) { getFoliaLib().getImpl().runLaterAsync(new UserPurgeTask(), 2 * Misc.TICK_CONVERSION_FACTOR); // Start 2 seconds after startup. - } - else if (purgeIntervalTicks > 0) { + } else if (purgeIntervalTicks > 0) { getFoliaLib().getImpl().runTimerAsync(new UserPurgeTask(), purgeIntervalTicks, purgeIntervalTicks); } // Automatically remove old members from parties - if(partyConfig.isPartyEnabled()) { + if (partyConfig.isPartyEnabled()) { long kickIntervalTicks = generalConfig.getAutoPartyKickInterval() * 60L * 60L * Misc.TICK_CONVERSION_FACTOR; if (kickIntervalTicks == 0) { @@ -688,8 +691,7 @@ public class mcMMO extends JavaPlugin { getFoliaLib().getImpl().runTimer(new ClearRegisteredXPGainTask(), 60, 60); } - if(mcMMO.p.getAdvancedConfig().allowPlayerTips()) - { + if (mcMMO.p.getAdvancedConfig().allowPlayerTips()) { getFoliaLib().getImpl().runTimer(new NotifySquelchReminderTask(), 60, ((20 * 60) * 60)); } } @@ -739,10 +741,6 @@ public class mcMMO extends JavaPlugin { return platformManager; } - public static SmeltingTracker getSmeltingTracker() { - return smeltingTracker; - } - public static BukkitAudiences getAudiences() { return audiences; } @@ -812,7 +810,23 @@ public class mcMMO extends JavaPlugin { return customItemSupportConfig; } + public PotionConfig getPotionConfig() { + return potionConfig; + } + + public EnchantmentMapper getEnchantmentMapper() { + return enchantmentMapper; + } + + public AttributeMapper getAttributeMapper() { + return attributeMapper; + } + public @NotNull FoliaLib getFoliaLib() { return foliaLib; } + +// public ProtocolLibManager getProtocolLibManager() { +// return protocolLibManager; +// } } diff --git a/src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java b/src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java deleted file mode 100644 index 1545cd608..000000000 --- a/src/main/java/com/gmail/nossr50/metadata/BlockMetadataService.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.gmail.nossr50.metadata; - -import com.gmail.nossr50.mcMMO; -import org.bukkit.block.Furnace; -import org.bukkit.persistence.PersistentDataContainer; -import org.bukkit.persistence.PersistentDataHolder; -import org.bukkit.persistence.PersistentDataType; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.UUID; - -import static com.gmail.nossr50.metadata.MetadataService.NSK_FURNACE_UUID_LEAST_SIG; -import static com.gmail.nossr50.metadata.MetadataService.NSK_FURNACE_UUID_MOST_SIG; - -public class BlockMetadataService { - - private final @NotNull mcMMO pluginRef; - - public BlockMetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; - } - - public @Nullable UUID getFurnaceOwner(@NotNull Furnace furnace) { - //Get container from entity - PersistentDataContainer dataContainer = ((PersistentDataHolder) furnace).getPersistentDataContainer(); - - //Too lazy to make a custom data type for this stuff - Long mostSigBits = dataContainer.get(NSK_FURNACE_UUID_MOST_SIG, PersistentDataType.LONG); - Long leastSigBits = dataContainer.get(NSK_FURNACE_UUID_LEAST_SIG, PersistentDataType.LONG); - - if (mostSigBits != null && leastSigBits != null) { - return new UUID(mostSigBits, leastSigBits); - } else { - return null; - } - } - - public void setFurnaceOwner(@NotNull Furnace furnace, @NotNull UUID uuid) { - PersistentDataContainer dataContainer = ((PersistentDataHolder) furnace).getPersistentDataContainer(); - - dataContainer.set(NSK_FURNACE_UUID_MOST_SIG, PersistentDataType.LONG, uuid.getMostSignificantBits()); - dataContainer.set(NSK_FURNACE_UUID_LEAST_SIG, PersistentDataType.LONG, uuid.getLeastSignificantBits()); - - furnace.update(); - } - - -} diff --git a/src/main/java/com/gmail/nossr50/metadata/MetadataService.java b/src/main/java/com/gmail/nossr50/metadata/MetadataService.java deleted file mode 100644 index d38726737..000000000 --- a/src/main/java/com/gmail/nossr50/metadata/MetadataService.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.gmail.nossr50.metadata; - -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.MetadataConstants; -import org.bukkit.NamespacedKey; -import org.jetbrains.annotations.NotNull; - -public class MetadataService { - private final @NotNull mcMMO pluginRef; - - protected static final @NotNull NamespacedKey NSK_SUPER_ABILITY_BOOSTED_ITEM; - protected static final @NotNull NamespacedKey NSK_MOB_SPAWNER_MOB; - protected static final @NotNull NamespacedKey NSK_EGG_MOB; - protected static final @NotNull NamespacedKey NSK_NETHER_GATE_MOB; - protected static final @NotNull NamespacedKey NSK_COTW_SUMMONED_MOB; - protected static final @NotNull NamespacedKey NSK_PLAYER_BRED_MOB; - protected static final @NotNull NamespacedKey NSK_PLAYER_TAMED_MOB; - protected static final @NotNull NamespacedKey NSK_VILLAGER_TRADE_ORIGIN_ITEM; - protected static final @NotNull NamespacedKey NSK_EXPLOITED_ENDERMEN; - protected static final @NotNull NamespacedKey NSK_FURNACE_UUID_MOST_SIG; - protected static final @NotNull NamespacedKey NSK_FURNACE_UUID_LEAST_SIG; - - static { - NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM); - NSK_MOB_SPAWNER_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB); - NSK_EGG_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_EGG_MOB); - NSK_NETHER_GATE_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB); - NSK_COTW_SUMMONED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB); - NSK_PLAYER_BRED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB); - NSK_PLAYER_TAMED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB); - NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM); - NSK_EXPLOITED_ENDERMEN = getNamespacedKey(MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN); - NSK_FURNACE_UUID_MOST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_FURNACE_UUID_MOST_SIG); - NSK_FURNACE_UUID_LEAST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_FURNACE_UUID_LEAST_SIG); - } - - private final @NotNull ItemMetadataService itemMetadataService; - private final @NotNull MobMetadataService mobMetadataService; - private final @NotNull BlockMetadataService blockMetadataService; - - public MetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; - - blockMetadataService = new BlockMetadataService(pluginRef); - mobMetadataService = new MobMetadataService(pluginRef); - itemMetadataService = new ItemMetadataService(pluginRef); - } - - /** - * Helper method to simplify generating namespaced keys - * - * @param key the {@link String} value of the key - * - * @return the generated {@link NamespacedKey} - */ - public static @NotNull NamespacedKey getNamespacedKey(@NotNull String key) { - return new NamespacedKey(mcMMO.p, key); - } - - public @NotNull ItemMetadataService getItemMetadataService() { - return itemMetadataService; - } - - public @NotNull MobMetadataService getMobMetadataService() { - return mobMetadataService; - } - - public @NotNull BlockMetadataService getBlockMetadataService() { - return blockMetadataService; - } -} diff --git a/src/main/java/com/gmail/nossr50/party/PartyManager.java b/src/main/java/com/gmail/nossr50/party/PartyManager.java index beff259d2..1a6300ac5 100644 --- a/src/main/java/com/gmail/nossr50/party/PartyManager.java +++ b/src/main/java/com/gmail/nossr50/party/PartyManager.java @@ -243,7 +243,7 @@ public final class PartyManager { } final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) + if (mmoPlayer == null) return null; return mmoPlayer.getParty(); diff --git a/src/main/java/com/gmail/nossr50/party/ShareHandler.java b/src/main/java/com/gmail/nossr50/party/ShareHandler.java index 24392e6b1..4719ebc36 100644 --- a/src/main/java/com/gmail/nossr50/party/ShareHandler.java +++ b/src/main/java/com/gmail/nossr50/party/ShareHandler.java @@ -51,8 +51,7 @@ public final class ShareHandler { for (Player member : nearMembers) { //Profile not loaded - if(UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -115,8 +114,7 @@ public final class ShareHandler { McMMOPlayer mcMMOMember = UserManager.getPlayer(member); //Profile not loaded - if(UserManager.getPlayer(member) == null) - { + if (UserManager.getPlayer(member) == null) { continue; } @@ -161,11 +159,9 @@ public final class ShareHandler { public static XPGainReason getSharedXpGainReason(XPGainReason xpGainReason) { if (xpGainReason == XPGainReason.PVE) { return XPGainReason.SHARED_PVE; - } - else if (xpGainReason == XPGainReason.PVP) { + } else if (xpGainReason == XPGainReason.PVP) { return XPGainReason.SHARED_PVP; - } - else { + } else { return xpGainReason; } } diff --git a/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java b/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java index 3f753bed9..bd301b52d 100644 --- a/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java +++ b/src/main/java/com/gmail/nossr50/placeholders/PartyLeaderPlaceholder.java @@ -1,6 +1,6 @@ package com.gmail.nossr50.placeholders; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.bukkit.entity.Player; public class PartyLeaderPlaceholder implements Placeholder { @@ -12,7 +12,7 @@ public class PartyLeaderPlaceholder implements Placeholder { @Override public String process(Player player, String params) { - return StringUtils.stripToEmpty(papiExpansion.getPartyLeader(player)); + return StringUtils.trimToEmpty(papiExpansion.getPartyLeader(player)); } @Override diff --git a/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java b/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java index 2cec030d6..e35346887 100644 --- a/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java +++ b/src/main/java/com/gmail/nossr50/placeholders/PartyNamePlaceholder.java @@ -1,6 +1,6 @@ package com.gmail.nossr50.placeholders; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.bukkit.entity.Player; public class PartyNamePlaceholder implements Placeholder { @@ -12,7 +12,7 @@ public class PartyNamePlaceholder implements Placeholder { @Override public String process(Player player, String params) { - return StringUtils.stripToEmpty(papiExpansion.getPartyName(player)); + return StringUtils.trimToEmpty(papiExpansion.getPartyName(player)); } @Override diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java new file mode 100644 index 000000000..bae3793f9 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/protocollib/ProtocolHandler.java @@ -0,0 +1,36 @@ +//package com.gmail.nossr50.protocollib; +// +//import com.comphenix.protocol.PacketType; +//import com.comphenix.protocol.ProtocolLibrary; +//import com.comphenix.protocol.ProtocolManager; +//import com.comphenix.protocol.events.ListenerPriority; +//import com.comphenix.protocol.events.PacketAdapter; +//import com.comphenix.protocol.events.PacketContainer; +//import com.comphenix.protocol.events.PacketEvent; +//import com.gmail.nossr50.mcMMO; +//import org.bukkit.entity.Player; +// +//public class ProtocolHandler { +// private final mcMMO pluginRef; +// private final ProtocolManager protocolManager; +// +// public ProtocolHandler(mcMMO pluginRef) { +// this.pluginRef = pluginRef; +// this.protocolManager = ProtocolLibrary.getProtocolManager(); +// // TODO: encapsulate this in a method +// protocolManager.addPacketListener(new PacketAdapter(pluginRef, ListenerPriority.NORMAL, PacketType.Play.Server.WINDOW_DATA) { +// @Override +// public void onPacketSending(PacketEvent event) { +// Player player = event.getPlayer(); +// PacketContainer packet = event.getPacket(); +// if (packet.getIntegers().read(0) == 400) { +// event.setCancelled(true); +// } +// } +// }); +// } +// public void sendPacketToPlayer(Player player) { +// final PacketContainer packet = protocolManager.createPacket(PacketType.Play.Server.WINDOW_DATA); +// protocolManager.sendServerPacket(player, packet); +// } +//} diff --git a/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java new file mode 100644 index 000000000..77f3c21bf --- /dev/null +++ b/src/main/java/com/gmail/nossr50/protocollib/ProtocolLibManager.java @@ -0,0 +1,40 @@ +//package com.gmail.nossr50.protocollib; +// +//import com.gmail.nossr50.mcMMO; +//import org.bukkit.Bukkit; +//import org.bukkit.entity.Player; +//import org.bukkit.plugin.Plugin; +// +//public class ProtocolLibManager { +// final Plugin protocolLibPluginRef; +// final mcMMO pluginRef; +// final ProtocolHandler protocolHandler; +// +// public ProtocolLibManager(mcMMO pluginRef) { +// this.pluginRef = pluginRef; +// +// if (isProtocolLibPresent()) { +// protocolLibPluginRef = pluginRef.getServer().getPluginManager().getPlugin("ProtocolLib"); +// protocolHandler = new ProtocolHandler(pluginRef); +// pluginRef.getLogger().info("ProtocolLib found, enabling ProtocolLib features."); +// } else { +// protocolLibPluginRef = null; +// protocolHandler = null; +// pluginRef.getLogger().info("No ProtocolLib found, some completely optional cosmetic features will not be enabled."); +// } +// } +// +// public boolean usingProtocolLib() { +// return protocolLibPluginRef != null && protocolHandler != null; +// } +// +// private boolean isProtocolLibPresent() { +// return Bukkit.getServer().getPluginManager().getPlugin("ProtocolLib") != null; +// } +// +// public void sendPacketToPlayer(Player player) { +// if (usingProtocolLib()) { +// protocolHandler.sendPacketToPlayer(player); +// } +// } +//} diff --git a/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java b/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java index 8087d3c65..cc0682910 100644 --- a/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java +++ b/src/main/java/com/gmail/nossr50/runnables/MobDodgeMetaCleanup.java @@ -17,7 +17,7 @@ public class MobDodgeMetaCleanup extends CancellableRunnable { @Override public void run() { - if(!mob.isValid() || mob.getTarget() == null) { + if (!mob.isValid() || mob.getTarget() == null) { mob.removeMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER, pluginRef); this.cancel(); } else if (!mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER)) { diff --git a/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java b/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java deleted file mode 100644 index d4e69c5bc..000000000 --- a/src/main/java/com/gmail/nossr50/runnables/PistonTrackerTask.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.gmail.nossr50.runnables; - -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.BlockUtils; -import com.gmail.nossr50.util.CancellableRunnable; -import com.gmail.nossr50.util.MetadataConstants; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; - -import java.util.List; - -public class PistonTrackerTask extends CancellableRunnable { - private final List blocks; - private final BlockFace direction; - private final Block futureEmptyBlock; - - public PistonTrackerTask(List blocks, BlockFace direction, Block futureEmptyBlock) { - this.blocks = blocks; - this.direction = direction; - this.futureEmptyBlock = futureEmptyBlock; - } - - @Override - public void run() { - // Check to see if futureEmptyBlock is empty - if it isn't; the blocks didn't move - if (!BlockUtils.isPistonPiece(futureEmptyBlock.getState())) { - return; - } - - if (mcMMO.getPlaceStore().isTrue(futureEmptyBlock)) { - mcMMO.getPlaceStore().setFalse(futureEmptyBlock); - } - - for (Block b : blocks) { - Block nextBlock = b.getRelative(direction); - - if (nextBlock.hasMetadata(MetadataConstants.METADATA_KEY_PISTON_TRACKING)) { - BlockUtils.setUnnaturalBlock(nextBlock); - nextBlock.removeMetadata(MetadataConstants.METADATA_KEY_PISTON_TRACKING, mcMMO.p); - } - else if (mcMMO.getPlaceStore().isTrue(nextBlock)) { - // Block doesn't have metadatakey but isTrue - set it to false - mcMMO.getPlaceStore().setFalse(nextBlock); - } - } - } -} diff --git a/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java b/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java index 613f3ecee..953c7d9ed 100644 --- a/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/SaveTimerTask.java @@ -19,7 +19,7 @@ public class SaveTimerTask extends CancellableRunnable { count++; } - if(mcMMO.p.getPartyConfig().isPartyEnabled()) + if (mcMMO.p.getPartyConfig().isPartyEnabled()) mcMMO.p.getPartyManager().saveParties(); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java b/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java index d8f52ae30..bf5c77269 100644 --- a/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/StickyPistonTrackerTask.java @@ -19,7 +19,7 @@ public class StickyPistonTrackerTask extends CancellableRunnable { @Override public void run() { - if (!mcMMO.getPlaceStore().isTrue(movedBlock.getRelative(direction))) { + if (!mcMMO.getUserBlockTracker().isIneligible(movedBlock.getRelative(direction))) { return; } @@ -29,7 +29,7 @@ public class StickyPistonTrackerTask extends CancellableRunnable { } // The sticky piston actually pulled the block so move the PlaceStore data - mcMMO.getPlaceStore().setFalse(movedBlock.getRelative(direction)); + mcMMO.getUserBlockTracker().setEligible(movedBlock.getRelative(direction)); BlockUtils.setUnnaturalBlock(movedBlock); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java b/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java index 366fb2967..e982201dc 100644 --- a/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java +++ b/src/main/java/com/gmail/nossr50/runnables/TravelingBlockMetaCleanup.java @@ -17,7 +17,7 @@ public class TravelingBlockMetaCleanup extends CancellableRunnable { @Override public void run() { - if(!entity.isValid()) { + if (!entity.isValid()) { entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); this.cancel(); } else if (!entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) { diff --git a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java index c4de1183d..f94295580 100644 --- a/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/backups/CleanBackupsTask.java @@ -51,13 +51,11 @@ public class CleanBackupsTask extends CancellableRunnable { if (isPast24Hours(date) && mcMMO.p.getGeneralConfig().getKeepLast24Hours()) { // Keep all files from the last 24 hours continue; - } - else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) { + } else if (isLastWeek(date) && !savedDays.contains(dayOfWeek) && mcMMO.p.getGeneralConfig().getKeepDailyLastWeek()) { // Keep daily backups of the past week savedDays.add(dayOfWeek); continue; - } - else { + } else { List savedWeeks = savedYearsWeeks.computeIfAbsent(year, k -> new ArrayList<>()); if (!savedWeeks.contains(weekOfYear) && mcMMO.p.getGeneralConfig().getKeepWeeklyPastMonth()) { diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java similarity index 88% rename from src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandAsyncTask.java rename to src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java index 2897b4388..4b24b329a 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McRankCommandAsyncTask.java @@ -3,18 +3,18 @@ package com.gmail.nossr50.runnables.commands; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; -import org.apache.commons.lang.Validate; +import org.apache.commons.lang3.Validate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Map; -public class McrankCommandAsyncTask extends CancellableRunnable { +public class McRankCommandAsyncTask extends CancellableRunnable { private final String playerName; private final CommandSender sender; private final boolean useBoard, useChat; - public McrankCommandAsyncTask(String playerName, CommandSender sender, boolean useBoard, boolean useChat) { + public McRankCommandAsyncTask(String playerName, CommandSender sender, boolean useBoard, boolean useChat) { Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java similarity index 89% rename from src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java rename to src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java index a343bc810..f0f0bc05e 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandAsyncTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McTopCommandAsyncTask.java @@ -4,19 +4,19 @@ import com.gmail.nossr50.datatypes.database.PlayerStat; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.CancellableRunnable; -import org.apache.commons.lang.Validate; +import org.apache.commons.lang3.Validate; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.List; -public class MctopCommandAsyncTask extends CancellableRunnable { +public class McTopCommandAsyncTask extends CancellableRunnable { private final CommandSender sender; private final PrimarySkillType skill; private final int page; private final boolean useBoard, useChat; - public MctopCommandAsyncTask(int page, PrimarySkillType skill, CommandSender sender, boolean useBoard, boolean useChat) { + public McTopCommandAsyncTask(int page, PrimarySkillType skill, CommandSender sender, boolean useBoard, boolean useChat) { Validate.isTrue(useBoard || useChat, "Attempted to start a rank retrieval with both board and chat off"); Validate.notNull(sender, "Attempted to start a rank retrieval with no recipient"); diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java index c1067ecf1..18fbb8854 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/McrankCommandDisplayTask.java @@ -64,8 +64,7 @@ public class McrankCommandDisplayTask extends CancellableRunnable { public void displayBoard() { if (sender.getName().equalsIgnoreCase(playerName)) { ScoreboardManager.showPlayerRankScoreboard((Player) sender, skills); - } - else { + } else { ScoreboardManager.showPlayerRankScoreboardOthers((Player) sender, playerName, skills); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java index ed1a2f73c..e2e491611 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/MctopCommandDisplayTask.java @@ -14,7 +14,7 @@ import org.bukkit.entity.Player; import java.util.List; /** - * Display the results of {@link MctopCommandAsyncTask} to the sender. + * Display the results of {@link McTopCommandAsyncTask} to the sender. */ public class MctopCommandDisplayTask extends CancellableRunnable { private final List userStats; @@ -45,25 +45,22 @@ public class MctopCommandDisplayTask extends CancellableRunnable { if (sender instanceof Player) { ((Player) sender).removeMetadata(MetadataConstants.METADATA_KEY_DATABASE_COMMAND, mcMMO.p); } - if(sender instanceof Player) + if (sender instanceof Player) sender.sendMessage(LocaleLoader.getString("Commands.mctop.Tip")); } private void displayChat() { if (skill == null) { - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.PowerLevel.Leaderboard")); - } - else { + } else { sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.PowerLevel.Leaderboard"))); } - } - else { - if(sender instanceof Player) { + } else { + if (sender instanceof Player) { sender.sendMessage(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill))); - } - else { + } else { sender.sendMessage(ChatColor.stripColor(LocaleLoader.getString("Commands.Skill.Leaderboard", mcMMO.p.getSkillTools().getLocalizedSkillName(skill)))); } } @@ -74,10 +71,9 @@ public class MctopCommandDisplayTask extends CancellableRunnable { // Format: // 01. Playername - skill value // 12. Playername - skill value - if(sender instanceof Player) { + if (sender instanceof Player) { sender.sendMessage(String.format("%2d. %s%s - %s%s", place, ChatColor.GREEN, stat.name, ChatColor.WHITE, stat.statVal)); - } - else { + } else { sender.sendMessage(String.format("%2d. %s - %s", place, stat.name, stat.statVal)); } @@ -88,8 +84,7 @@ public class MctopCommandDisplayTask extends CancellableRunnable { private void displayBoard() { if (skill == null) { ScoreboardManager.showTopPowerScoreboard((Player) sender, page, userStats); - } - else { + } else { ScoreboardManager.showTopScoreboard((Player) sender, skill, page, userStats); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java index 9b9fcd6fe..83faca3dd 100644 --- a/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/commands/NotifySquelchReminderTask.java @@ -11,10 +11,8 @@ public class NotifySquelchReminderTask extends CancellableRunnable { @Override public void run() { for (Player player : Bukkit.getOnlinePlayers()) { - if(UserManager.getPlayer(player) != null) - { - if(!UserManager.getPlayer(player).useChatNotifications()) - { + if (UserManager.getPlayer(player) != null) { + if (!UserManager.getPlayer(player).useChatNotifications()) { player.sendMessage(LocaleLoader.getString("Reminder.Squelched")); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java index 214d4e58b..71ea24ea1 100644 --- a/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/database/FormulaConversionTask.java @@ -44,8 +44,7 @@ public class FormulaConversionTask extends CancellableRunnable { editValues(profile); // Since this is a temporary profile, we save it here. profile.scheduleAsyncSave(); - } - else { + } else { profile = mcMMOPlayer.getProfile(); editValues(profile); } diff --git a/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java b/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java index 25d809f59..362731101 100644 --- a/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java +++ b/src/main/java/com/gmail/nossr50/runnables/items/TeleportationWarmup.java @@ -60,8 +60,7 @@ public class TeleportationWarmup extends CancellableRunnable { if (!Permissions.partyTeleportWorld(targetPlayer, targetWorld)) { teleportingPlayer.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; - } - else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(teleportingPlayer, targetWorld)) { + } else if (targetWorld != playerWorld && !Permissions.partyTeleportWorld(teleportingPlayer, targetWorld)) { teleportingPlayer.sendMessage(LocaleLoader.getString("Commands.ptp.NoWorldPermissions", targetWorld.getName())); return; } diff --git a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java index 6cd865055..42bcad967 100644 --- a/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/player/PlayerProfileLoadingTask.java @@ -44,7 +44,7 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { PlayerProfile profile = mcMMO.getDatabaseManager().loadPlayerProfile(player); - if(!profile.isLoaded()) { + if (!profile.isLoaded()) { LogUtils.debug(mcMMO.p.getLogger(), "Creating new data for player: "+player.getName()); //Profile isn't loaded so add as new user profile = mcMMO.getDatabaseManager().newUser(player); @@ -58,8 +58,7 @@ public class PlayerProfileLoadingTask extends CancellableRunnable { } // Print errors to console/logs if we're failing at least 2 times in a row to load the profile - if (attempt >= 3) - { + if (attempt >= 3) { //Log the error mcMMO.p.getLogger().severe(LocaleLoader.getString("Profile.Loading.FailureNotice", player.getName(), String.valueOf(attempt))); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java index a789171e0..3e63e5a89 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AbilityDisableTask.java @@ -62,7 +62,7 @@ public class AbilityDisableTask extends CancellableRunnable { if (mcMMO.p.getAdvancedConfig().sendAbilityNotificationToOtherPlayers()) { SkillUtils.sendSkillMessage(player, NotificationType.SUPER_ABILITY_ALERT_OTHERS, ability.getAbilityPlayerOff()); } - if(!mcMMO.isServerShutdownExecuted()) { + if (!mcMMO.isServerShutdownExecuted()) { mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(player, new AbilityCooldownTask(mcMMOPlayer, ability), (long) PerksUtils.handleCooldownPerks(player, ability.getCooldown()) * Misc.TICK_CONVERSION_FACTOR); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java index 68de298f5..640b498e8 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewCheckTask.java @@ -1,39 +1,59 @@ package com.gmail.nossr50.runnables.skills; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.skills.alchemy.Alchemy; -import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; import com.gmail.nossr50.util.CancellableRunnable; +import com.gmail.nossr50.util.ContainerMetadataUtils; +import com.gmail.nossr50.util.player.UserManager; import org.bukkit.Location; +import org.bukkit.OfflinePlayer; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Arrays; +import static com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer.isValidBrew; + public class AlchemyBrewCheckTask extends CancellableRunnable { - private final Player player; private final BrewingStand brewingStand; private final ItemStack[] oldInventory; - public AlchemyBrewCheckTask(Player player, BrewingStand brewingStand) { - this.player = player; + @Deprecated(forRemoval = true, since = "2.2.010") + public AlchemyBrewCheckTask(@Nullable Player ignored, BrewingStand brewingStand) { + this(brewingStand); + } + + public AlchemyBrewCheckTask(@NotNull BrewingStand brewingStand) { this.brewingStand = brewingStand; this.oldInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); } @Override public void run() { - Location location = brewingStand.getLocation(); - ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); - boolean validBrew = brewingStand.getFuelLevel() > 0 && AlchemyPotionBrewer.isValidBrew(player, newInventory); - - if (Alchemy.brewingStandMap.containsKey(location)) { - if (oldInventory[Alchemy.INGREDIENT_SLOT] == null || newInventory[Alchemy.INGREDIENT_SLOT] == null || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) || !validBrew) { - Alchemy.brewingStandMap.get(location).cancelBrew(); + OfflinePlayer offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); + int ingredientLevel = 1; + if (offlinePlayer != null && offlinePlayer.isOnline()) { + final McMMOPlayer mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + if (mmoPlayer != null) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); } } - else if (validBrew) { - Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand, player)); + final Location location = brewingStand.getLocation(); + final ItemStack[] newInventory = Arrays.copyOfRange(brewingStand.getInventory().getContents(), 0, 4); + boolean validBrew = brewingStand.getFuelLevel() > 0 && isValidBrew(ingredientLevel, newInventory); + + if (Alchemy.brewingStandMap.containsKey(location)) { + if (oldInventory[Alchemy.INGREDIENT_SLOT] == null + || newInventory[Alchemy.INGREDIENT_SLOT] == null + || !oldInventory[Alchemy.INGREDIENT_SLOT].isSimilar(newInventory[Alchemy.INGREDIENT_SLOT]) + || !validBrew) { + Alchemy.brewingStandMap.get(location).cancelBrew(); + } + } else if (validBrew) { + Alchemy.brewingStandMap.put(location, new AlchemyBrewTask(brewingStand)); } } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java index de5ea2adb..34c192852 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AlchemyBrewTask.java @@ -1,5 +1,6 @@ package com.gmail.nossr50.runnables.skills; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.events.skills.alchemy.McMMOPlayerBrewEvent; @@ -8,43 +9,56 @@ import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.alchemy.Alchemy; import com.gmail.nossr50.skills.alchemy.AlchemyPotionBrewer; import com.gmail.nossr50.util.CancellableRunnable; +import com.gmail.nossr50.util.ContainerMetadataUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.Location; import org.bukkit.Material; +import org.bukkit.OfflinePlayer; import org.bukkit.block.BlockState; import org.bukkit.block.BrewingStand; import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; public class AlchemyBrewTask extends CancellableRunnable { private static final double DEFAULT_BREW_SPEED = 1.0; private static final int DEFAULT_BREW_TICKS = 400; private final BlockState brewingStand; - private final Location location; + private final OfflinePlayer offlinePlayer; + private McMMOPlayer mmoPlayer; private double brewSpeed; private double brewTimer; - private final Player player; private int fuel; private boolean firstRun = true; + private int ingredientLevel = 1; + + @Deprecated(forRemoval = true, since = "2.2.010") + public AlchemyBrewTask(@NotNull BlockState brewingStand, Player ignored) { + this(brewingStand); + } + + public AlchemyBrewTask(@NotNull BlockState brewingStand) { + offlinePlayer = ContainerMetadataUtils.getContainerOwner(brewingStand); + McMMOPlayer mmoPlayer = null; + if (offlinePlayer != null && offlinePlayer.isOnline()) { + mmoPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + } - public AlchemyBrewTask(BlockState brewingStand, Player player) { this.brewingStand = brewingStand; - this.location = brewingStand.getLocation(); - this.player = player; brewSpeed = DEFAULT_BREW_SPEED; brewTimer = DEFAULT_BREW_TICKS; - if (player != null - && !Misc.isNPCEntityExcludingVillagers(player) - && Permissions.isSubSkillEnabled(player, SubSkillType.ALCHEMY_CATALYSIS) - && UserManager.getPlayer(player) != null) { + if (mmoPlayer != null + && !Misc.isNPCEntityExcludingVillagers(mmoPlayer.getPlayer()) + && Permissions.isSubSkillEnabled(mmoPlayer.getPlayer(), SubSkillType.ALCHEMY_CATALYSIS)) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); - double catalysis = UserManager.getPlayer(player).getAlchemyManager().calculateBrewSpeed(Permissions.lucky(player, PrimarySkillType.ALCHEMY)); + double catalysis = mmoPlayer.getAlchemyManager().calculateBrewSpeed(Permissions.lucky(mmoPlayer.getPlayer(), + PrimarySkillType.ALCHEMY)); - McMMOPlayerCatalysisEvent event = new McMMOPlayerCatalysisEvent(player, catalysis); + McMMOPlayerCatalysisEvent event = new McMMOPlayerCatalysisEvent(mmoPlayer, catalysis); mcMMO.p.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { @@ -52,8 +66,8 @@ public class AlchemyBrewTask extends CancellableRunnable { } } - if (Alchemy.brewingStandMap.containsKey(location)) { - Alchemy.brewingStandMap.get(location).cancel(); + if (Alchemy.brewingStandMap.containsKey(brewingStand.getLocation())) { + Alchemy.brewingStandMap.get(brewingStand.getLocation()).cancel(); } fuel = ((BrewingStand) brewingStand).getFuelLevel(); @@ -61,61 +75,104 @@ public class AlchemyBrewTask extends CancellableRunnable { if (((BrewingStand) brewingStand).getBrewingTime() == -1) // Only decrement on our end if it isn't a vanilla ingredient. fuel--; - Alchemy.brewingStandMap.put(location, this); - mcMMO.p.getFoliaLib().getImpl().runAtLocationTimer(location, this, 1, 1); + Alchemy.brewingStandMap.put(brewingStand.getLocation(), this); + mcMMO.p.getFoliaLib().getImpl().runAtLocationTimer(brewingStand.getLocation(), this, 1, 1); } @Override public void run() { - if (player == null || !player.isValid() || brewingStand == null || brewingStand.getType() != Material.BREWING_STAND || !AlchemyPotionBrewer.isValidIngredient(player, ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT])) { - if (Alchemy.brewingStandMap.containsKey(location)) { - Alchemy.brewingStandMap.remove(location); + // Check if preconditions for brewing are not met + if (shouldCancelBrewing()) { + if (Alchemy.brewingStandMap.containsKey(brewingStand.getLocation())) { + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } - this.cancel(); - return; } + // Initialize the brewing stand on the first run + initializeBrewing(); + + // Update the brewing process timer + brewTimer -= brewSpeed; + + // Check if the brewing process should finish + if (isBrewingComplete()) { + this.cancel(); + finish(); + } else { + updateBrewingTime(); + } + } + + private boolean shouldCancelBrewing() { + if (offlinePlayer == null) { + return true; + } + if (brewingStand == null) { + return true; + } + if (brewingStand.getType() != Material.BREWING_STAND) { + return true; + } + return !AlchemyPotionBrewer.isValidIngredientByLevel( + getIngredientLevelUpdated(), ((BrewingStand) brewingStand).getInventory().getContents()[Alchemy.INGREDIENT_SLOT]); + } + + private int getIngredientLevelUpdated() { + if (mmoPlayer != null) { + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + return ingredientLevel; + } else if (offlinePlayer.isOnline() && mmoPlayer == null) { + final McMMOPlayer fetchedMMOPlayer = UserManager.getPlayer(offlinePlayer.getPlayer()); + if (fetchedMMOPlayer != null) { + this.mmoPlayer = fetchedMMOPlayer; + ingredientLevel = mmoPlayer.getAlchemyManager().getTier(); + } + return ingredientLevel; + } else { + return ingredientLevel; + } + } + + private void initializeBrewing() { if (firstRun) { firstRun = false; ((BrewingStand) brewingStand).setFuelLevel(fuel); } - - brewTimer -= brewSpeed; - - // Vanilla potion brewing completes when BrewingTime == 1 - if (brewTimer < Math.max(brewSpeed, 2)) { - this.cancel(); - finish(); - } - else { - ((BrewingStand) brewingStand).setBrewingTime((int) brewTimer); - } } + private boolean isBrewingComplete() { + return brewTimer < Math.max(brewSpeed, 2); + } + + private void updateBrewingTime() { + ((BrewingStand) brewingStand).setBrewingTime((int) brewTimer); + } + + private void finish() { - McMMOPlayerBrewEvent event = new McMMOPlayerBrewEvent(player, brewingStand); + final McMMOPlayerBrewEvent event = new McMMOPlayerBrewEvent(mmoPlayer, brewingStand); mcMMO.p.getServer().getPluginManager().callEvent(event); if (!event.isCancelled()) { - AlchemyPotionBrewer.finishBrewing(brewingStand, player, false); + AlchemyPotionBrewer.finishBrewing(brewingStand, mmoPlayer.getPlayer(), false); } - Alchemy.brewingStandMap.remove(location); + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } public void finishImmediately() { this.cancel(); - AlchemyPotionBrewer.finishBrewing(brewingStand, player, true); - Alchemy.brewingStandMap.remove(location); + AlchemyPotionBrewer.finishBrewing(brewingStand, mmoPlayer.getPlayer(), true); + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } public void cancelBrew() { this.cancel(); ((BrewingStand) brewingStand).setBrewingTime(-1); - Alchemy.brewingStandMap.remove(location); + Alchemy.brewingStandMap.remove(brewingStand.getLocation()); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java index 6ced4c66a..bd2e4ae1c 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/AwardCombatXpTask.java @@ -40,7 +40,7 @@ public class AwardCombatXpTask extends CancellableRunnable { damage += health; } - if(ExperienceConfig.getInstance().useCombatHPCeiling()) { + if (ExperienceConfig.getInstance().useCombatHPCeiling()) { damage = Math.min(damage, ExperienceConfig.getInstance().getCombatHPCeiling()); } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java index 32b4b9eca..3dd31ad93 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedContainer.java @@ -9,8 +9,7 @@ public class BleedContainer { public LivingEntity target; public LivingEntity damageSource; - public BleedContainer(LivingEntity target, int bleedTicks, int bleedRank, int toolTier, LivingEntity damageSource) - { + public BleedContainer(LivingEntity target, int bleedTicks, int bleedRank, int toolTier, LivingEntity damageSource) { this.target = target; this.bleedTicks = bleedTicks; this.bleedRank = bleedRank; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java index 0cb4d3d13..f67fa1e86 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/BleedTimerTask.java @@ -43,7 +43,7 @@ //// debugMessage+="RemainingTicks=["+containerEntry.getValue().bleedTicks+"], "; // // if (containerEntry.getValue().bleedTicks <= 0 || !target.isValid()) { -// if(target instanceof Player) +// if (target instanceof Player) // { // NotificationManager.sendPlayerInformation((Player) target, NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Bleeding.Stopped"); // } @@ -96,7 +96,7 @@ // //// debugMessage+="FullArmor=["+String.valueOf(armorCount > 3)+"], "; // -// if(armorCount > 3) +// if (armorCount > 3) // { // damage = damage * .75; // } @@ -104,13 +104,13 @@ //// debugMessage+="AfterRankAndArmorChecks["+damage+"], "; // // //Weapons below Diamond get damage cut in half -// if(toolTier < 4) +// if (toolTier < 4) // damage = damage / 2; // //// debugMessage+="AfterDiamondCheck=["+String.valueOf(damage)+"], "; // // //Wood weapons get damage cut in half again -// if(toolTier < 2) +// if (toolTier < 2) // damage = damage / 2; // //// debugMessage+="AfterWoodenCheck=["+String.valueOf(damage)+"], "; @@ -129,7 +129,7 @@ // //// debugMessage+="TargetHealthAfterDMG=["+String.valueOf(target.getHealth())+"], "; // -// if(victimHealthAftermath <= 0 || victimHealth != victimHealthAftermath) +// if (victimHealthAftermath <= 0 || victimHealth != victimHealthAftermath) // { // //Play Bleed Sound // SoundManager.worldSendSound(target.getWorld(), target.getLocation(), SoundType.BLEED); @@ -187,7 +187,7 @@ // throw new IllegalStateException("Cannot add bleed task async!"); // } // -// if(isIterating) { +// if (isIterating) { // //Used to throw an error here, but in reality all we are really doing is preventing concurrency issues from other plugins being naughty and its not really needed // //I'm not really a fan of silent errors, but I'm sick of seeing people using crazy enchantments come in and report this "bug" // return; @@ -195,7 +195,7 @@ // //// if (isIterating) throw new IllegalStateException("Cannot add task while iterating timers!"); // -// if(toolTier < 4) +// if (toolTier < 4) // ticks = Math.max(1, (ticks / 3)); // // ticks+=1; diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java index 927e9a3f8..ecbe6e43f 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/DelayedCropReplant.java @@ -35,7 +35,7 @@ public class DelayedCropReplant extends CancellableRunnable { public DelayedCropReplant(BlockBreakEvent blockBreakEvent, BlockState cropState, int desiredCropAge, boolean wasImmaturePlant) { BlockData cropData = cropState.getBlockData(); - if(cropData instanceof Directional cropDir) { + if (cropData instanceof Directional cropDir) { cropFace = cropDir.getFacing(); } @@ -56,13 +56,13 @@ public class DelayedCropReplant extends CancellableRunnable { //Remove the metadata marking the block as recently replanted mcMMO.p.getFoliaLib().getImpl().runAtLocationLater(blockBreakEvent.getBlock().getLocation(), new markPlantAsOld(blockBreakEvent.getBlock().getLocation()), 10); - if(blockBreakEvent.isCancelled()) { + if (blockBreakEvent.isCancelled()) { wasImmaturePlant = true; } //Two kinds of air in Minecraft - if(currentState.getType().equals(cropMaterial) || currentState.getType().equals(Material.AIR) || currentState.getType().equals(Material.CAVE_AIR)) { -// if(currentState.getBlock().getRelative(BlockFace.DOWN)) + if (currentState.getType().equals(cropMaterial) || currentState.getType().equals(Material.AIR) || currentState.getType().equals(Material.CAVE_AIR)) { +// if (currentState.getBlock().getRelative(BlockFace.DOWN)) //The space is not currently occupied by a block so we can fill it cropBlock.setType(cropMaterial); @@ -74,19 +74,19 @@ public class DelayedCropReplant extends CancellableRunnable { int age = 0; //Crop age should always be 0 if the plant was immature - if(!wasImmaturePlant) { + if (!wasImmaturePlant) { age = desiredCropAge; //Otherwise make the plant the desired age } - if(newData instanceof Directional) { + if (newData instanceof Directional) { //Cocoa Version Directional directional = (Directional) newState.getBlockData(); directional.setFacing(cropFace); newState.setBlockData(directional); - if(newData instanceof Cocoa) { + if (newData instanceof Cocoa) { plantAnchorType = PlantAnchorType.COCOA; } } @@ -119,7 +119,7 @@ public class DelayedCropReplant extends CancellableRunnable { this.plantBlock = plantBlock; this.plantAnchorType = plantAnchorType; - if(plantFace != null) { + if (plantFace != null) { this.plantFace = plantFace; } } @@ -140,8 +140,8 @@ public class DelayedCropReplant extends CancellableRunnable { private void checkPlantIntegrity(@NotNull BlockFace blockFace) { Block neighbor = plantBlock.getRelative(blockFace); - if(plantAnchorType == PlantAnchorType.COCOA) { - if(!neighbor.getType().toString().toLowerCase().contains("jungle")) { + if (plantAnchorType == PlantAnchorType.COCOA) { + if (!neighbor.getType().toString().toLowerCase().contains("jungle")) { plantBlock.breakNaturally(); } } else { @@ -171,7 +171,7 @@ public class DelayedCropReplant extends CancellableRunnable { @Override public void run() { Block cropBlock = cropLoc.getBlock(); - if(cropBlock.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() > 0) + if (cropBlock.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() > 0) cropBlock.setMetadata(MetadataConstants.METADATA_KEY_REPLANT, new RecentlyReplantedCropMeta(mcMMO.p, false)); } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java index 34c87b0d4..e5da7e81b 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/ExperienceBarHideTask.java @@ -10,8 +10,7 @@ public class ExperienceBarHideTask extends CancellableRunnable { public final PrimarySkillType primarySkillType; public final ExperienceBarManager experienceBarManagerRef; - public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) - { + public ExperienceBarHideTask(ExperienceBarManager experienceBarManagerRef, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType) { this.experienceBarManagerRef = experienceBarManagerRef; this.mcMMOPlayer = mcMMOPlayer; this.primarySkillType = primarySkillType; @@ -30,7 +29,7 @@ public class ExperienceBarHideTask extends CancellableRunnable { */ @Override public void run() { - if(experienceBarManagerRef == null || mcMMOPlayer == null) + if (experienceBarManagerRef == null || mcMMOPlayer == null) return; experienceBarManagerRef.hideExperienceBar(primarySkillType); diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java index 432d5a296..56dc1b406 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/RuptureTask.java @@ -42,15 +42,15 @@ public class RuptureTask extends CancellableRunnable { @Override public void run() { //Check validity - if(targetEntity.isValid()) { + if (targetEntity.isValid()) { ruptureTick += 1; //Advance rupture tick by 1. damageTickTracker += 1; //Increment damage tick tracker //TODO: Clean this code up, applyRupture() is a confusing name for something that returns boolean //Rupture hasn't ended yet - if(ruptureTick < expireTick) { + if (ruptureTick < expireTick) { //Is it time to damage? - if(damageTickTracker >= DAMAGE_TICK_INTERVAL) { + if (damageTickTracker >= DAMAGE_TICK_INTERVAL) { damageTickTracker = 0; //Reset timer if (applyRupture()) return; @@ -58,7 +58,7 @@ public class RuptureTask extends CancellableRunnable { playAnimation(); } } else { - if(!applyRupture()) { + if (!applyRupture()) { playAnimation(); } @@ -71,7 +71,7 @@ public class RuptureTask extends CancellableRunnable { } private void playAnimation() { - if(animationTick >= ANIMATION_TICK_INTERVAL) { + if (animationTick >= ANIMATION_TICK_INTERVAL) { ParticleEffectUtils.playBleedEffect(targetEntity); //Animate animationTick = 0; } else { @@ -114,7 +114,7 @@ public class RuptureTask extends CancellableRunnable { // // ParticleEffectUtils.playGreaterImpactEffect(targetEntity); //Animate // -// if(ruptureSource.getPlayer() != null && ruptureSource.getPlayer().isValid()) { +// if (ruptureSource.getPlayer() != null && ruptureSource.getPlayer().isValid()) { // targetEntity.damage(getExplosionDamage(), ruptureSource.getPlayer()); // } else { // targetEntity.damage(getExplosionDamage(), null); @@ -129,10 +129,10 @@ public class RuptureTask extends CancellableRunnable { private double calculateAdjustedTickDamage() { double tickDamage = pureTickDamage; - if(targetEntity.getHealth() <= tickDamage) { + if (targetEntity.getHealth() <= tickDamage) { tickDamage = targetEntity.getHealth() - 0.01; - if(tickDamage <= 0) { + if (tickDamage <= 0) { tickDamage = 0; } } diff --git a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java index c9b6d87a5..eea79ed31 100644 --- a/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java +++ b/src/main/java/com/gmail/nossr50/runnables/skills/SkillUnlockNotificationTask.java @@ -16,8 +16,7 @@ public class SkillUnlockNotificationTask extends CancellableRunnable { * @param subSkillType the subskill that they just unlocked * @param rank the rank of the subskill */ - public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) - { + public SkillUnlockNotificationTask(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType, int rank) { this.mcMMOPlayer = mcMMOPlayer; this.subSkillType = subSkillType; this.rank = rank; diff --git a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java index 08fd39ab4..e9529751f 100644 --- a/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/acrobatics/AcrobaticsManager.java @@ -14,6 +14,7 @@ import com.gmail.nossr50.util.MetadataConstants; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.player.NotificationManager; +import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.ParticleEffectUtils; import com.gmail.nossr50.util.skills.RankUtils; @@ -38,23 +39,19 @@ public class AcrobaticsManager extends SkillManager { private long rollXPIntervalLengthen = (1000 * 10); //10 Seconds private final BlockLocationHistory fallLocationMap; - public boolean hasFallenInLocationBefore(Location location) - { + public boolean hasFallenInLocationBefore(Location location) { return fallLocationMap.contains(location); } - public void addLocationToFallMap(Location location) - { + public void addLocationToFallMap(Location location) { fallLocationMap.add(location); } - public boolean canGainRollXP() - { - if(!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) + public boolean canGainRollXP() { + if (!ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) return true; - if(System.currentTimeMillis() >= rollXPCooldown) - { + if (System.currentTimeMillis() >= rollXPCooldown) { rollXPCooldown = System.currentTimeMillis() + rollXPInterval; rollXPIntervalLengthen = (1000 * 10); //5 Seconds return true; @@ -66,10 +63,10 @@ public class AcrobaticsManager extends SkillManager { } public boolean canDodge(Entity damager) { - if(getPlayer().isBlocking()) + if (getPlayer().isBlocking()) return false; - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ACROBATICS_DODGE)) return false; if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ACROBATICS_DODGE)) { @@ -94,7 +91,7 @@ public class AcrobaticsManager extends SkillManager { Player player = getPlayer(); if (!isFatal(modifiedDamage) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_DODGE, player)) { + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ACROBATICS_DODGE, UserManager.getPlayer(player))) { ParticleEffectUtils.playDodgeEffect(player); if (mmoPlayer.useChatNotifications()) { @@ -102,14 +99,14 @@ public class AcrobaticsManager extends SkillManager { } if (SkillUtils.cooldownExpired(mmoPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { - if(attacker instanceof Mob mob) { + if (attacker instanceof Mob mob) { //Check to see how many dodge XP rewards this mob has handed out - if(mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER) && ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { + if (mob.hasMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER) && ExperienceConfig.getInstance().isAcrobaticsExploitingPrevented()) { //If Dodge XP has been handed out 5 times then consider it being exploited MetadataValue metadataValue = mob.getMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER).get(0); int count = metadataValue.asInt(); - if(count <= 5) { + if (count <= 5) { applyXpGain((float) (damage * Acrobatics.dodgeXpModifier), XPGainReason.PVE); mob.setMetadata(MetadataConstants.METADATA_KEY_DODGE_TRACKER, new FixedMetadataValue(mcMMO.p, count + 1)); MobDodgeMetaCleanup metaCleanupTask = new MobDodgeMetaCleanup(mob, mcMMO.p); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java index c6c5470a3..d921bc3a2 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/Alchemy.java @@ -11,40 +11,6 @@ import java.util.List; import java.util.Map; public final class Alchemy { - /*public enum Tier { - EIGHT(8), - SEVEN(7), - SIX(6), - FIVE(5), - FOUR(4), - THREE(3), - TWO(2), - ONE(1); - - int numerical; - - private Tier(int numerical) { - this.numerical = numerical; - } - - public int toNumerical() { - return numerical; - } - - public static Tier fromNumerical(int numerical) { - for (Tier tier : Tier.values()) { - if (tier.toNumerical() == numerical) { - return tier; - } - } - return null; - } - - protected int getLevel() { - return mcMMO.p.getAdvancedConfig().getConcoctionsTierLevel(this); - } - }*/ - public static final int INGREDIENT_SLOT = 3; public static int catalysisMaxBonusLevel = mcMMO.p.getAdvancedConfig().getCatalysisMaxBonusLevel(); diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java index 16b1dd2ac..8cc53bc5b 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyManager.java @@ -1,13 +1,13 @@ package com.gmail.nossr50.skills.alchemy; import com.gmail.nossr50.config.experience.ExperienceConfig; -import com.gmail.nossr50.config.skills.alchemy.PotionConfig; import com.gmail.nossr50.datatypes.experience.XPGainReason; import com.gmail.nossr50.datatypes.experience.XPGainSource; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; +import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.text.StringUtils; @@ -27,7 +27,7 @@ public class AlchemyManager extends SkillManager { } public List getIngredients() { - return PotionConfig.getInstance().getIngredients(getTier()); + return mcMMO.p.getPotionConfig().getIngredients(getTier()); } public String getIngredientList() { @@ -52,6 +52,11 @@ public class AlchemyManager extends SkillManager { return Math.min(Alchemy.catalysisMaxSpeed, Alchemy.catalysisMinSpeed + (Alchemy.catalysisMaxSpeed - Alchemy.catalysisMinSpeed) * (skillLevel - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS)) / (Alchemy.catalysisMaxBonusLevel - RankUtils.getUnlockLevel(SubSkillType.ALCHEMY_CATALYSIS))) * (isLucky ? LUCKY_MODIFIER : 1.0); } + /** + * Handle the XP gain for a successful potion brew. + * @param potionStage The potion stage, this is used to determine the XP gain. + * @param amount The amount of potions brewed. + */ public void handlePotionBrewSuccesses(PotionStage potionStage, int amount) { applyXpGain((float) (ExperienceConfig.getInstance().getPotionXP(potionStage) * amount), XPGainReason.PVE, XPGainSource.PASSIVE); } diff --git a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java index 2a11b0159..573dbd4c6 100644 --- a/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java +++ b/src/main/java/com/gmail/nossr50/skills/alchemy/AlchemyPotionBrewer.java @@ -1,6 +1,6 @@ package com.gmail.nossr50.skills.alchemy; -import com.gmail.nossr50.config.skills.alchemy.PotionConfig; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.alchemy.AlchemyPotion; import com.gmail.nossr50.datatypes.skills.alchemy.PotionStage; @@ -20,23 +20,51 @@ import org.bukkit.inventory.BrewerInventory; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; +// TODO: Update to use McMMOPlayer public final class AlchemyPotionBrewer { + @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isValidBrew(Player player, ItemStack[] contents) { - if (!isValidIngredient(player, contents[Alchemy.INGREDIENT_SLOT])) { + if (!isValidIngredientByPlayer(player, contents[Alchemy.INGREDIENT_SLOT])) { return false; } for (int i = 0; i < 3; i++) { - if (contents[i] == null || contents[i].getType() != Material.POTION && contents[i].getType() != Material.SPLASH_POTION && contents[i].getType() != Material.LINGERING_POTION) { + if (contents[i] == null || contents[i].getType() != Material.POTION + && contents[i].getType() != Material.SPLASH_POTION + && contents[i].getType() != Material.LINGERING_POTION) { continue; } - if (getChildPotion(PotionConfig.getInstance().getPotion(contents[i]), contents[Alchemy.INGREDIENT_SLOT]) != null) { + final AlchemyPotion potion = mcMMO.p.getPotionConfig().getPotion(contents[i]); + if (getChildPotion(potion, contents[Alchemy.INGREDIENT_SLOT]) != null) { + return true; + } + } + + return false; + } + + public static boolean isValidBrew(int ingredientLevel, ItemStack[] contents) { + if (!isValidIngredientByLevel(ingredientLevel, contents[Alchemy.INGREDIENT_SLOT])) { + return false; + } + + for (int i = 0; i < 3; i++) { + if (contents[i] == null || contents[i].getType() != Material.POTION + && contents[i].getType() != Material.SPLASH_POTION + && contents[i].getType() != Material.LINGERING_POTION) { + continue; + } + + final AlchemyPotion potion = mcMMO.p.getPotionConfig().getPotion(contents[i]); + if (getChildPotion(potion, contents[Alchemy.INGREDIENT_SLOT]) != null) { return true; } } @@ -57,16 +85,15 @@ public final class AlchemyPotionBrewer { } private static void removeIngredient(BrewerInventory inventory, Player player) { - if(inventory.getIngredient() == null) + if (inventory.getIngredient() == null) return; ItemStack ingredient = inventory.getIngredient().clone(); - if (!isEmpty(ingredient) && isValidIngredient(player, ingredient)) { + if (!isEmpty(ingredient) && isValidIngredientByPlayer(player, ingredient)) { if (ingredient.getAmount() <= 1) { inventory.setIngredient(null); - } - else { + } else { ingredient.setAmount(ingredient.getAmount() - 1); inventory.setIngredient(ingredient); } @@ -76,15 +103,15 @@ public final class AlchemyPotionBrewer { private static boolean hasIngredient(BrewerInventory inventory, Player player) { ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); - return !isEmpty(ingredient) && isValidIngredient(player, ingredient); + return !isEmpty(ingredient) && isValidIngredientByPlayer(player, ingredient); } - public static boolean isValidIngredient(Player player, ItemStack item) { + public static boolean isValidIngredientByPlayer(Player player, ItemStack item) { if (isEmpty(item)) { return false; } - for (ItemStack ingredient : getValidIngredients(player)) { + for (ItemStack ingredient : getValidIngredients(UserManager.getPlayer(player))) { if (item.isSimilar(ingredient)) { return true; } @@ -93,62 +120,96 @@ public final class AlchemyPotionBrewer { return false; } - private static List getValidIngredients(Player player) { - if(player == null || UserManager.getPlayer(player) == null) - { - return PotionConfig.getInstance().getIngredients(1); + public static boolean isValidIngredientByLevel(int ingredientLevel, ItemStack item) { + if (isEmpty(item)) { + return false; } - return PotionConfig.getInstance().getIngredients(!Permissions.isSubSkillEnabled(player, SubSkillType.ALCHEMY_CONCOCTIONS) ? 1 : UserManager.getPlayer(player).getAlchemyManager().getTier()); + // TODO: Update this when we fix loading from hoppers + for (ItemStack ingredient : mcMMO.p.getPotionConfig().getIngredients(ingredientLevel)) { + if (item.isSimilar(ingredient)) { + return true; + } + } + + return false; + } + + private static List getValidIngredients(@Nullable McMMOPlayer mmoPlayer) { + if (mmoPlayer == null) { + return mcMMO.p.getPotionConfig().getIngredients(1); + } + + return mcMMO.p.getPotionConfig().getIngredients(!Permissions.isSubSkillEnabled(mmoPlayer, SubSkillType.ALCHEMY_CONCOCTIONS) + ? 1 : mmoPlayer.getAlchemyManager().getTier()); } public static void finishBrewing(BlockState brewingStand, Player player, boolean forced) { + // Check if the brewing stand block state is an actual brewing stand if (!(brewingStand instanceof BrewingStand)) { return; } - BrewerInventory inventory = ((BrewingStand) brewingStand).getInventory(); - ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); + // Retrieve the inventory of the brewing stand and clone the current ingredient for safe manipulation + final BrewerInventory inventory = ((BrewingStand) brewingStand).getInventory(); + final ItemStack ingredient = inventory.getIngredient() == null ? null : inventory.getIngredient().clone(); + // Check if the brewing stand has a valid ingredient; if not, exit the method if (!hasIngredient(inventory, player)) { + // debug return; } + // Initialize lists to hold the potions before and after brewing, initially setting them to null List inputList = new ArrayList<>(Collections.nCopies(3, null)); List outputList = new ArrayList<>(Collections.nCopies(3, null)); + // Process each of the three slots in the brewing stand for (int i = 0; i < 3; i++) { ItemStack item = inventory.getItem(i); - if (isEmpty(item) || item.getType() == Material.GLASS_BOTTLE || !PotionConfig.getInstance().isValidPotion(item)) { + // Skip the slot if it's empty, contains a glass bottle, or holds an invalid potion + if (isEmpty(item) + || item.getType() == Material.GLASS_BOTTLE + || !mcMMO.p.getPotionConfig().isValidPotion(item)) { + // debug continue; } - AlchemyPotion input = PotionConfig.getInstance().getPotion(item); + // Retrieve the potion configurations for the input and resulting output potion + AlchemyPotion input = mcMMO.p.getPotionConfig().getPotion(item); AlchemyPotion output = input.getChild(ingredient); + // Update the input list with the current potion inputList.set(i, input); + // If there is a valid output potion, add it to the output list if (output != null) { outputList.set(i, output.toItemStack(item.getAmount()).clone()); } } + // Create a fake brewing event and pass it to the plugin's event system FakeBrewEvent event = new FakeBrewEvent(brewingStand.getBlock(), inventory, outputList, ((BrewingStand) brewingStand).getFuelLevel()); mcMMO.p.getServer().getPluginManager().callEvent(event); + // If the event is cancelled or there are no potions processed, exit the method if (event.isCancelled() || inputList.isEmpty()) { + // debug return; } + // Update the brewing inventory with the new potions for (int i = 0; i < 3; i++) { - if(outputList.get(i) != null) { + if (outputList.get(i) != null) { inventory.setItem(i, outputList.get(i)); } } + // Remove the used ingredient from the brewing inventory removeIngredient(inventory, player); + // Handle potion brewing success and related effects for each potion processed for (AlchemyPotion input : inputList) { if (input == null) continue; @@ -157,13 +218,14 @@ public final class AlchemyPotionBrewer { if (output != null && player != null) { PotionStage potionStage = PotionStage.getPotionStage(input, output); - //TODO: hmm - if (UserManager.hasPlayerDataKey(player)) { + // Update player alchemy skills or effects based on brewing success + if (UserManager.getPlayer(player) != null) { UserManager.getPlayer(player).getAlchemyManager().handlePotionBrewSuccesses(potionStage, 1); } } } + // If the brewing was not forced by external conditions, schedule a new update if (!forced) { scheduleUpdate(inventory); } @@ -174,8 +236,7 @@ public final class AlchemyPotionBrewer { if (click.isLeftClick()) { success = transferItems(view, fromSlot); - } - else if (click.isRightClick()) { + } else if (click.isRightClick()) { success = transferOneItem(view, fromSlot); } @@ -195,13 +256,11 @@ public final class AlchemyPotionBrewer { if (!emptyTo && fromAmount >= from.getType().getMaxStackSize()) { return false; - } - else if (emptyTo || from.isSimilar(to)) { + } else if (emptyTo || from.isSimilar(to)) { if (emptyTo) { to = from.clone(); to.setAmount(1); - } - else { + } else { to.setAmount(to.getAmount() + 1); } @@ -224,14 +283,12 @@ public final class AlchemyPotionBrewer { if (isEmpty(from)) { return false; - } - else if (isEmpty(to)) { + } else if (isEmpty(to)) { view.setItem(Alchemy.INGREDIENT_SLOT, from); view.setItem(fromSlot, null); return true; - } - else if (from.isSimilar(to)) { + } else if (from.isSimilar(to)) { int fromAmount = from.getAmount(); int toAmount = to.getAmount(); int maxSize = to.getType().getMaxStackSize(); @@ -258,8 +315,9 @@ public final class AlchemyPotionBrewer { return false; } - public static void scheduleCheck(Player player, BrewingStand brewingStand) { - mcMMO.p.getFoliaLib().getImpl().runAtEntity(player, new AlchemyBrewCheckTask(player, brewingStand)); + public static void scheduleCheck(@NotNull BrewingStand brewingStand) { + mcMMO.p.getFoliaLib().getImpl().runAtLocation( + brewingStand.getLocation(), new AlchemyBrewCheckTask(brewingStand)); } public static void scheduleUpdate(Inventory inventory) { diff --git a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java index 3ad317287..d5cf998e8 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/Archery.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/Archery.java @@ -64,8 +64,7 @@ public class Archery { } } - public static double getSkillShotBonusDamage(Player player, double oldDamage) - { + public static double getSkillShotBonusDamage(Player player, double oldDamage) { double damageBonusPercent = getDamageBonusPercent(player); double newDamage = oldDamage + (oldDamage * damageBonusPercent); return Math.min(newDamage, (oldDamage + Archery.skillShotMaxBonusDamage)); diff --git a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java index 7cc028e8f..785fafd46 100644 --- a/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java +++ b/src/main/java/com/gmail/nossr50/skills/archery/ArcheryManager.java @@ -18,7 +18,8 @@ import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; + +import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; public class ArcheryManager extends SkillManager { public ArcheryManager(McMMOPlayer mcMMOPlayer) { @@ -26,21 +27,21 @@ public class ArcheryManager extends SkillManager { } public boolean canDaze(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_DAZE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_DAZE)) return false; return target instanceof Player && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_DAZE); } public boolean canSkillShot() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_SKILL_SHOT); } public boolean canRetrieveArrows() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.ARCHERY_ARROW_RETRIEVAL); @@ -54,13 +55,13 @@ public class ArcheryManager extends SkillManager { */ public static double distanceXpBonusMultiplier(LivingEntity target, Entity arrow) { //Hacky Fix - some plugins spawn arrows and assign them to players after the ProjectileLaunchEvent fires - if(!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) + if (!arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) return 1; Location firedLocation = (Location) arrow.getMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE).get(0).value(); Location targetLocation = target.getLocation(); - if(firedLocation == null || firedLocation.getWorld() == null) + if (firedLocation == null || firedLocation.getWorld() == null) return 1; if (firedLocation.getWorld() != targetLocation.getWorld()) { @@ -76,7 +77,7 @@ public class ArcheryManager extends SkillManager { * @param target The {@link LivingEntity} damaged by the arrow */ public void retrieveArrows(LivingEntity target, Projectile projectile) { - if(projectile.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { + if (projectile.hasMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW)) { Archery.incrementTrackerValue(target); projectile.removeMetadata(MetadataConstants.METADATA_KEY_TRACKED_ARROW, mcMMO.p); //Only 1 entity per projectile } @@ -88,17 +89,15 @@ public class ArcheryManager extends SkillManager { * @param defender The {@link Player} being affected by the ability */ public double daze(Player defender) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_DAZE, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.ARCHERY_DAZE, mmoPlayer)) { return 0; } Location dazedLocation = defender.getLocation(); dazedLocation.setPitch(90 - Misc.getRandom().nextInt(181)); -// defender.teleport(dazedLocation); mcMMO.p.getFoliaLib().getImpl().teleportAsync(defender, dazedLocation); - defender.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 20 * 10, 10)); - + defender.addPotionEffect(new PotionEffect(getNauseaPotionEffectType(), 20 * 10, 10)); if (NotificationManager.doesPlayerUseNotifications(defender)) { NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Combat.TouchedFuzzy"); @@ -117,7 +116,7 @@ public class ArcheryManager extends SkillManager { * @param oldDamage The raw damage value of this arrow before we modify it */ public double skillShot(double oldDamage) { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.ARCHERY_SKILL_SHOT, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.ARCHERY_SKILL_SHOT, mmoPlayer)) { return Archery.getSkillShotBonusDamage(getPlayer(), oldDamage); } else { return oldDamage; diff --git a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java index 47d95be3f..0ea49854c 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/Axes.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/Axes.java @@ -23,11 +23,11 @@ public class Axes { public static double skullSplitterModifier = mcMMO.p.getAdvancedConfig().getSkullSplitterModifier(); protected static boolean hasArmor(LivingEntity target) { - if(target == null || !target.isValid() || target.getEquipment() == null) + if (target == null || !target.isValid() || target.getEquipment() == null) return false; for (ItemStack itemStack : target.getEquipment().getArmorContents()) { - if(itemStack == null) + if (itemStack == null) continue; if (ItemUtils.isArmor(itemStack)) { @@ -43,8 +43,7 @@ public class Axes { * @param player The target player * @return The axe mastery bonus damage which will be added to their attack */ - public static double getAxeMasteryBonusDamage(Player player) - { + public static double getAxeMasteryBonusDamage(Player player) { return RankUtils.getRank(player, SubSkillType.AXES_AXE_MASTERY) * Axes.axeMasteryRankDamageMultiplier; } } diff --git a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java index d80f7292f..9fc75038a 100644 --- a/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java +++ b/src/main/java/com/gmail/nossr50/skills/axes/AxesManager.java @@ -18,6 +18,7 @@ import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; +import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; @@ -27,35 +28,35 @@ public class AxesManager extends SkillManager { } public boolean canUseAxeMastery() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_AXE_MASTERY)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_AXE_MASTERY)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_AXE_MASTERY); } public boolean canCriticalHit(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_CRITICAL_STRIKES); } public boolean canImpact(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_ARMOR_IMPACT) && Axes.hasArmor(target); } public boolean canGreaterImpact(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_GREATER_IMPACT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_GREATER_IMPACT)) return false; return target.isValid() && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.AXES_GREATER_IMPACT) && !Axes.hasArmor(target); } public boolean canUseSkullSplitter(@NotNull LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.AXES_SKULL_SPLITTER)) return false; return target.isValid() && mmoPlayer.getAbilityMode(SuperAbilityType.SKULL_SPLITTER) && Permissions.skullSplitter(getPlayer()); @@ -69,7 +70,7 @@ public class AxesManager extends SkillManager { * Handle the effects of the Axe Mastery ability */ public double axeMastery() { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.AXES_AXE_MASTERY, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.AXES_AXE_MASTERY, mmoPlayer)) { return Axes.getAxeMasteryBonusDamage(getPlayer()); } @@ -83,7 +84,7 @@ public class AxesManager extends SkillManager { * @param damage The amount of damage initially dealt by the event */ public double criticalHit(LivingEntity target, double damage) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_CRITICAL_STRIKES, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_CRITICAL_STRIKES, mmoPlayer)) { return 0; } @@ -100,8 +101,7 @@ public class AxesManager extends SkillManager { } damage = (damage * Axes.criticalHitPVPModifier) - damage; - } - else { + } else { damage = (damage * Axes.criticalHitPVEModifier) - damage; } @@ -115,10 +115,15 @@ public class AxesManager extends SkillManager { */ public void impactCheck(@NotNull LivingEntity target) { double durabilityDamage = getImpactDurabilityDamage(); + final EntityEquipment equipment = target.getEquipment(); - for (ItemStack armor : target.getEquipment().getArmorContents()) { + if (equipment == null) { + return; + } + + for (ItemStack armor : equipment.getArmorContents()) { if (armor != null && ItemUtils.isArmor(armor)) { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_ARMOR_IMPACT, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_ARMOR_IMPACT, mmoPlayer)) { SkillUtils.handleArmorDurabilityChange(armor, durabilityDamage, 1); } } @@ -136,7 +141,7 @@ public class AxesManager extends SkillManager { */ public double greaterImpact(@NotNull LivingEntity target) { //static chance (3rd param) - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_GREATER_IMPACT, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.AXES_GREATER_IMPACT, mmoPlayer)) { return 0; } diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java b/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java index a64b023af..1a60efd7d 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/Crossbows.java @@ -31,7 +31,7 @@ public class Crossbows { } private static void processTrickShot(ProjectileHitEvent event, Plugin pluginRef, Arrow arrow, McMMOPlayer mmoPlayer) { - if(event.getHitBlock() != null && event.getHitBlockFace() != null) { + if (event.getHitBlock() != null && event.getHitBlockFace() != null) { mmoPlayer.getCrossbowsManager().handleRicochet( pluginRef, arrow, diff --git a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java index 75d7e5d23..1858f6368 100644 --- a/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/crossbows/CrossbowsManager.java @@ -28,7 +28,7 @@ public class CrossbowsManager extends SkillManager { } public void handleRicochet(@NotNull Plugin pluginRef, @NotNull Arrow arrow, @NotNull Vector hitBlockNormal) { - if(!arrow.isShotFromCrossbow()) + if (!arrow.isShotFromCrossbow()) return; // Check player permission @@ -88,8 +88,7 @@ public class CrossbowsManager extends SkillManager { return RankUtils.getRank(mmoPlayer, SubSkillType.CROSSBOWS_TRICK_SHOT); } - public double getPoweredShotBonusDamage(Player player, double oldDamage) - { + public double getPoweredShotBonusDamage(Player player, double oldDamage) { double damageBonusPercent = getDamageBonusPercent(player); double newDamage = oldDamage + (oldDamage * damageBonusPercent); return Math.min(newDamage, (oldDamage + mcMMO.p.getAdvancedConfig().getPoweredShotDamageMax())); @@ -100,7 +99,7 @@ public class CrossbowsManager extends SkillManager { } public double poweredShot(double oldDamage) { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.CROSSBOWS_POWERED_SHOT, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.CROSSBOWS_POWERED_SHOT, mmoPlayer)) { return getPoweredShotBonusDamage(getPlayer(), oldDamage); } else { return oldDamage; diff --git a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java index e3cf20fd3..434b675b1 100644 --- a/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java +++ b/src/main/java/com/gmail/nossr50/skills/excavation/ExcavationManager.java @@ -46,7 +46,8 @@ public class ExcavationManager extends SkillManager { for (ExcavationTreasure treasure : treasures) { if (skillLevel >= treasure.getDropLevel() - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.EXCAVATION, getPlayer(), treasure.getDropProbability())) { + && ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.EXCAVATION, mmoPlayer, treasure.getDropProbability())) { processExcavationBonusesOnBlock(blockState, treasure, location); } } @@ -65,7 +66,8 @@ public class ExcavationManager extends SkillManager { @VisibleForTesting public void processExcavationBonusesOnBlock(BlockState blockState, ExcavationTreasure treasure, Location location) { //Spawn Vanilla XP orbs if a dice roll succeeds - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.EXCAVATION, getPlayer(), getArchaelogyExperienceOrbChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.EXCAVATION, mmoPlayer, getArchaelogyExperienceOrbChance())) { Misc.spawnExperienceOrb(location, getExperienceOrbsReward()); } @@ -89,8 +91,7 @@ public class ExcavationManager extends SkillManager { return RankUtils.getRank(getPlayer(), SubSkillType.EXCAVATION_ARCHAEOLOGY); } - public void printExcavationDebug(Player player, BlockState blockState) - { + public void printExcavationDebug(Player player, BlockState blockState) { if (Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.EXCAVATION_ARCHAEOLOGY)) { List treasures = Excavation.getTreasures(blockState); diff --git a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java index 6063add73..7dbf66221 100644 --- a/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/fishing/FishingManager.java @@ -74,15 +74,15 @@ public class FishingManager extends SkillManager { // { // long currentTime = System.currentTimeMillis(); // //Only track spam casting if the fishing hook is fresh -// if(currentTime > fishHookSpawnTimestamp + 1000) +// if (currentTime > fishHookSpawnTimestamp + 1000) // return; // -// if(currentTime < fishingRodCastTimestamp + FISHING_ROD_CAST_CD_MILLISECONDS) +// if (currentTime < fishingRodCastTimestamp + FISHING_ROD_CAST_CD_MILLISECONDS) // { // ItemStack fishingRod = getPlayer().getInventory().getItemInMainHand(); // // //Ensure correct hand item is damaged -// if(fishingRod.getType() != Material.FISHING_ROD) { +// if (fishingRod.getType() != Material.FISHING_ROD) { // fishingRod = getPlayer().getInventory().getItemInOffHand(); // } // @@ -90,7 +90,7 @@ public class FishingManager extends SkillManager { // fishingRod.setDurability((short) (fishingRod.getDurability() + 5)); // getPlayer().updateInventory(); // -// if(lastWarnedExhaust + (1000) < currentTime) +// if (lastWarnedExhaust + (1000) < currentTime) // { // getPlayer().sendMessage(LocaleLoader.getString("Fishing.Exhausting")); // lastWarnedExhaust = currentTime; @@ -101,9 +101,8 @@ public class FishingManager extends SkillManager { // fishingRodCastTimestamp = System.currentTimeMillis(); // } - public void setFishHookReference(FishHook fishHook) - { - if(fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) + public void setFishHookReference(FishHook fishHook) { + if (fishHook.getMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF).size() > 0) return; fishHook.setMetadata(MetadataConstants.METADATA_KEY_FISH_HOOK_REF, MetadataConstants.MCMMO_METADATA_VALUE); @@ -113,14 +112,12 @@ public class FishingManager extends SkillManager { } - public boolean isFishingTooOften() - { + public boolean isFishingTooOften() { long currentTime = System.currentTimeMillis(); long fishHookSpawnCD = fishHookSpawnTimestamp + 1000; boolean hasFished = (currentTime < fishHookSpawnCD); - if(hasFished && (lastWarned + (1000) < currentTime)) - { + if (hasFished && (lastWarned + (1000) < currentTime)) { getPlayer().sendMessage(LocaleLoader.getString("Fishing.Scared")); lastWarned = System.currentTimeMillis(); } @@ -134,8 +131,7 @@ public class FishingManager extends SkillManager { if (this.sameTarget) { fishCaughtCounter++; - } - else { + } else { fishCaughtCounter = 1; } @@ -257,7 +253,7 @@ public class FishingManager extends SkillManager { public void processMasterAngler(@NotNull FishHook fishHook, int lureLevel) { MasterAnglerCompatibilityLayer masterAnglerCompatibilityLayer = (MasterAnglerCompatibilityLayer) mcMMO.getCompatibilityManager().getMasterAnglerCompatibilityLayer(); - if(masterAnglerCompatibilityLayer != null) { + if (masterAnglerCompatibilityLayer != null) { int maxWaitTicks = masterAnglerCompatibilityLayer.getMaxWaitTime(fishHook); int minWaitTicks = masterAnglerCompatibilityLayer.getMinWaitTime(fishHook); @@ -265,7 +261,7 @@ public class FishingManager extends SkillManager { int convertedLureBonus = 0; //This avoids a Minecraft bug where lure levels above 3 break fishing - if(lureLevel > 0) { + if (lureLevel > 0) { masterAnglerCompatibilityLayer.setApplyLure(fishHook, false); convertedLureBonus = lureLevel * 100; } @@ -284,15 +280,15 @@ public class FishingManager extends SkillManager { boolean badValuesFix = false; //If we find bad values correct it - if(reducedMaxWaitTime < reducedMinWaitTime) { + if (reducedMaxWaitTime < reducedMinWaitTime) { reducedMaxWaitTime = reducedMinWaitTime + 100; badValuesFix = true; } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage(ChatColor.GOLD + "Master Angler Debug"); - if(badValuesFix) { + if (badValuesFix) { mmoPlayer.getPlayer().sendMessage(ChatColor.RED + "Bad values were applied and corrected, check your configs, max wait should never be lower than min wait."); } @@ -301,7 +297,7 @@ public class FishingManager extends SkillManager { mmoPlayer.getPlayer().sendMessage("MAX TICK REDUCTION: " + maxWaitReduction); mmoPlayer.getPlayer().sendMessage("BOAT BONUS: " + boatBonus); - if(boatBonus) { + if (boatBonus) { mmoPlayer.getPlayer().sendMessage("BOAT MAX TICK REDUCTION: " + maxWaitReduction); mmoPlayer.getPlayer().sendMessage("BOAT MIN TICK REDUCTION: " + maxWaitReduction); } @@ -341,7 +337,7 @@ public class FishingManager extends SkillManager { public int getMasterAnglerTickMaxWaitReduction(int masterAnglerRank, boolean boatBonus, int emulatedLureBonus) { int totalBonus = mcMMO.p.getAdvancedConfig().getFishingReductionMaxWaitTicks() * masterAnglerRank; - if(boatBonus) { + if (boatBonus) { totalBonus += getFishingBoatMaxWaitReduction(); } @@ -353,7 +349,7 @@ public class FishingManager extends SkillManager { public int getMasterAnglerTickMinWaitReduction(int masterAnglerRank, boolean boatBonus) { int totalBonus = mcMMO.p.getAdvancedConfig().getFishingReductionMinWaitTicks() * masterAnglerRank; - if(boatBonus) { + if (boatBonus) { totalBonus += getFishingBoatMinWaitReduction(); } @@ -394,7 +390,7 @@ public class FishingManager extends SkillManager { } if (treasure != null) { - if(treasure instanceof FishingTreasureBook) { + if (treasure instanceof FishingTreasureBook) { treasureDrop = ItemUtils.createEnchantBook((FishingTreasureBook) treasure); } else { treasureDrop = treasure.getDrop().clone(); // Not cloning is bad, m'kay? @@ -406,19 +402,19 @@ public class FishingManager extends SkillManager { /* * Books get some special treatment */ - if(treasure instanceof FishingTreasureBook) { + if (treasure instanceof FishingTreasureBook) { //Skip the magic hunter stuff - if(treasureDrop.getItemMeta() != null) { + if (treasureDrop.getItemMeta() != null) { enchants.putAll(treasureDrop.getItemMeta().getEnchants()); } - event = EventUtils.callFishingTreasureEvent(player, treasureDrop, treasure.getXp(), enchants); + event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, treasure.getXp(), enchants); } else { if (isMagicHunterEnabled() && ItemUtils.isEnchantable(treasureDrop)) { enchants = processMagicHunter(treasureDrop); } - event = EventUtils.callFishingTreasureEvent(player, treasureDrop, treasure.getXp(), enchants); + event = EventUtils.callFishingTreasureEvent(mmoPlayer, treasureDrop, treasure.getXp(), enchants); } if (!event.isCancelled()) { @@ -430,7 +426,7 @@ public class FishingManager extends SkillManager { fishingSucceeds = true; boolean enchanted = false; - if(treasure instanceof FishingTreasureBook) { + if (treasure instanceof FishingTreasureBook) { enchanted = true; } else if (!enchants.isEmpty()) { treasureDrop.addUnsafeEnchantments(enchants); @@ -448,7 +444,7 @@ public class FishingManager extends SkillManager { } } - if(fishingSucceeds) { + if (fishingSucceeds) { if (mcMMO.p.getGeneralConfig().getFishingExtraFish()) { Misc.spawnItem(getPlayer(), player.getEyeLocation(), fishingCatch.getItemStack(), ItemSpawnReason.FISHING_EXTRA_FISH); } @@ -480,7 +476,7 @@ public class FishingManager extends SkillManager { * @param target The {@link LivingEntity} affected by the ability */ public void shakeCheck(@NotNull LivingEntity target) { - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.FISHING, getPlayer(), getShakeChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.FISHING, mmoPlayer, getShakeChance())) { List possibleDrops = Fishing.findPossibleDrops(target); if (possibleDrops == null || possibleDrops.isEmpty()) { @@ -520,8 +516,7 @@ public class FishingManager extends SkillManager { if (FishingTreasureConfig.getInstance().getInventoryStealStacks()) { inventory.setItem(slot, null); - } - else { + } else { inventory.setItem(slot, (drop.getAmount() > 1) ? new ItemStack(drop.getType(), drop.getAmount() - 1) : null); drop.setAmount(1); } @@ -573,11 +568,12 @@ public class FishingManager extends SkillManager { int luck; if (getPlayer().getInventory().getItemInMainHand().getType() == Material.FISHING_ROD) { - luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel(Enchantment.LUCK); - } - else { + luck = getPlayer().getInventory().getItemInMainHand().getEnchantmentLevel( + mcMMO.p.getEnchantmentMapper().getLuckOfTheSea()); + } else { // We know something was caught, so if the rod wasn't in the main hand it must be in the offhand - luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel(Enchantment.LUCK); + luck = getPlayer().getInventory().getItemInOffHand().getEnchantmentLevel( + mcMMO.p.getEnchantmentMapper().getLuckOfTheSea()); } // Rather than subtracting luck (and causing a minimum 3% chance for every drop), scale by luck. diff --git a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java index c75f03a1a..adbdf2a84 100644 --- a/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java +++ b/src/main/java/com/gmail/nossr50/skills/herbalism/HerbalismManager.java @@ -33,7 +33,6 @@ import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.data.Ageable; import org.bukkit.block.data.BlockData; -import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.inventory.ItemStack; @@ -44,6 +43,7 @@ import java.util.*; import static com.gmail.nossr50.util.ItemUtils.hasItemIncludingOffHand; import static com.gmail.nossr50.util.ItemUtils.removeItemIncludingOffHand; +import static java.util.Objects.requireNonNull; public class HerbalismManager extends SkillManager { public HerbalismManager(McMMOPlayer mcMMOPlayer) { @@ -51,7 +51,7 @@ public class HerbalismManager extends SkillManager { } public boolean canGreenThumbBlock(BlockState blockState) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB)) return false; Player player = getPlayer(); @@ -61,11 +61,11 @@ public class HerbalismManager extends SkillManager { } public boolean canUseShroomThumb(BlockState blockState) { - if(!BlockUtils.canMakeShroomy(blockState)) { + if (!BlockUtils.canMakeShroomy(blockState)) { return false; } - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_SHROOM_THUMB)) return false; Player player = getPlayer(); @@ -81,29 +81,29 @@ public class HerbalismManager extends SkillManager { public void processBerryBushHarvesting(@NotNull BlockState blockState) { /* Check if the player is harvesting a berry bush */ - if(blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { - if(mmoPlayer.isDebugMode()) { + if (blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Processing sweet berry bush rewards"); } //Check the age - if(blockState.getBlockData() instanceof Ageable ageable) { + if (blockState.getBlockData() instanceof Ageable ageable) { int rewardByAge = 0; - if(ageable.getAge() == 2) { + if (ageable.getAge() == 2) { rewardByAge = 1; //Normal XP - } else if(ageable.getAge() == 3) { + } else if (ageable.getAge() == 3) { rewardByAge = 2; //Double XP } else { return; //Not old enough, back out of processing } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Bush Reward Multiplier: " + rewardByAge); } int xpReward = ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, blockState) * rewardByAge; - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Bush XP: " + xpReward); } @@ -129,10 +129,10 @@ public class HerbalismManager extends SkillManager { public void run() { BlockState blockState = block.getState(); - if(blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { - if(blockState.getBlockData() instanceof Ageable ageable) { + if (blockState.getType().toString().equalsIgnoreCase("sweet_berry_bush")) { + if (blockState.getBlockData() instanceof Ageable ageable) { - if(ageable.getAge() <= 1) { + if (ageable.getAge() <= 1) { applyXpGain(xpReward, XPGainReason.PVE, XPGainSource.SELF); } } @@ -142,7 +142,7 @@ public class HerbalismManager extends SkillManager { public boolean canUseHylianLuck() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.HERBALISM_HYLIAN_LUCK); @@ -207,17 +207,17 @@ public class HerbalismManager extends SkillManager { Block block = blockBreakEvent.getBlock(); if (mcMMO.p.getGeneralConfig().getHerbalismPreventAFK() && player.isInsideVehicle()) { - if(block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { + if (block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } return; } //Check if the plant was recently replanted - if(block.getBlockData() instanceof Ageable ageableCrop) { - if(block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() >= 1) { - if(block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).get(0).asBoolean()) { - if(isAgeableMature(ageableCrop)) { + if (block.getBlockData() instanceof Ageable ageableCrop) { + if (block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).size() >= 1) { + if (block.getMetadata(MetadataConstants.METADATA_KEY_REPLANT).get(0).asBoolean()) { + if (isAgeableMature(ageableCrop)) { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } else { //Crop is recently replanted to back out of destroying it @@ -236,7 +236,7 @@ public class HerbalismManager extends SkillManager { //Grab all broken blocks HashSet brokenBlocks = getBrokenHerbalismBlocks(blockBreakEvent); - if(brokenBlocks.size() == 0) + if (brokenBlocks.size() == 0) return; //Handle rewards, xp, ability interactions, etc @@ -249,16 +249,16 @@ public class HerbalismManager extends SkillManager { * @param brokenPlants plant blocks to process */ private void processHerbalismOnBlocksBroken(BlockBreakEvent blockBreakEvent, HashSet brokenPlants) { - if(blockBreakEvent.isCancelled()) + if (blockBreakEvent.isCancelled()) return; BlockState originalBreak = blockBreakEvent.getBlock().getState(); boolean greenThumbActivated = false; //TODO: The design of Green Terra needs to change, this is a mess - if(Permissions.greenThumbPlant(getPlayer(), originalBreak.getType())) { - if(mcMMO.p.getGeneralConfig().isGreenThumbReplantableCrop(originalBreak.getType())) { - if(!getPlayer().isSneaking()) { + if (Permissions.greenThumbPlant(getPlayer(), originalBreak.getType())) { + if (mcMMO.p.getGeneralConfig().isGreenThumbReplantableCrop(originalBreak.getType())) { + if (!getPlayer().isSneaking()) { greenThumbActivated = processGreenThumbPlants(originalBreak, blockBreakEvent, isGreenTerraActive()); } } @@ -279,21 +279,21 @@ public class HerbalismManager extends SkillManager { /* * This check is to make XP bars appear to work properly with Chorus Trees by giving XP for the originalBreak immediately instead of later */ - if(brokenPlant.getLocation().equals(originalBreak.getBlock().getLocation())) { + if (brokenPlant.getLocation().equals(originalBreak.getBlock().getLocation())) { //If its the same block as the original, we are going to directly check it for being a valid XP gain and add it to the nonChorusBlocks list even if its a chorus block //This stops a delay from happening when bringing up the XP bar for chorus trees - if(!mcMMO.getPlaceStore().isTrue(originalBreak)) { + if (!mcMMO.getUserBlockTracker().isIneligible(originalBreak)) { //Even if its a chorus block, the original break will be moved to nonChorusBlocks for immediate XP rewards noDelayPlantBlocks.add(brokenPlant); } else { - if(isChorusTree(brokenPlant.getType())) { + if (isChorusTree(brokenPlant.getType())) { //If its a chorus tree AND it was marked as true in the placestore then we add this block to the list of chorus blocks delayedChorusBlocks.add(new BlockSnapshot(brokenPlant.getType(), brokenPlant)); } else { noDelayPlantBlocks.add(brokenPlant); //If its not a chorus plant that was marked as unnatural but it was marked unnatural, put it in the nodelay list to be handled } } - } else if(isChorusTree(brokenPlant.getType())) { + } else if (isChorusTree(brokenPlant.getType())) { //Chorus Blocks get checked for XP several ticks later to avoid expensive calculations delayedChorusBlocks.add(new BlockSnapshot(brokenPlant.getType(), brokenPlant)); } else { @@ -302,12 +302,12 @@ public class HerbalismManager extends SkillManager { } //Give out XP to the non-chorus blocks - if(noDelayPlantBlocks.size() > 0) { + if (noDelayPlantBlocks.size() > 0) { //Note: Will contain 1 chorus block if the original block was a chorus block, this is to prevent delays for the XP bar awardXPForPlantBlocks(noDelayPlantBlocks); } - if(delayedChorusBlocks.size() > 0) { + if (delayedChorusBlocks.size() > 0) { //Check XP for chorus blocks DelayedHerbalismXPCheckTask delayedHerbalismXPCheckTask = new DelayedHerbalismXPCheckTask(mmoPlayer, delayedChorusBlocks); @@ -335,7 +335,7 @@ public class HerbalismManager extends SkillManager { BlockData plantData = brokenPlantState.getBlockData(); //Check for double drops - if(!mcMMO.getPlaceStore().isTrue(brokenPlant)) { + if (!mcMMO.getUserBlockTracker().isIneligible(brokenPlant)) { /* * @@ -346,14 +346,14 @@ public class HerbalismManager extends SkillManager { */ //Not all things that are natural should give double drops, make sure its fully mature as well - if(plantData instanceof Ageable ageable) { + if (plantData instanceof Ageable ageable) { - if(isAgeableMature(ageable) || isBizarreAgeable(plantData)) { - if(checkDoubleDrop(brokenPlantState)) { + if (isAgeableMature(ageable) || isBizarreAgeable(plantData)) { + if (checkDoubleDrop(brokenPlantState)) { markForBonusDrops(brokenPlantState); } } - } else if(checkDoubleDrop(brokenPlantState)) { + } else if (checkDoubleDrop(brokenPlantState)) { //Add metadata to mark this block for double or triple drops markForBonusDrops(brokenPlantState); } @@ -366,7 +366,7 @@ public class HerbalismManager extends SkillManager { */ //If it's a Crop we need to reward XP when its fully grown - if(isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { + if (isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { //Add metadata to mark this block for double or triple drops markForBonusDrops(brokenPlantState); } @@ -380,7 +380,7 @@ public class HerbalismManager extends SkillManager { * @return returns true if the BlockData is a bizarre ageable for Herbalism XP / Rewards */ public boolean isBizarreAgeable(BlockData blockData) { - if(blockData instanceof Ageable) { + if (blockData instanceof Ageable) { //Catcus and Sugar Canes cannot be trusted return switch (blockData.getMaterial()) { case CACTUS, KELP, SUGAR_CANE, BAMBOO -> true; @@ -413,7 +413,7 @@ public class HerbalismManager extends SkillManager { BlockState brokenBlockNewState = brokenPlantBlock.getState(); BlockData plantData = brokenBlockNewState.getBlockData(); - if(mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { + if (mcMMO.getUserBlockTracker().isIneligible(brokenBlockNewState)) { /* * * Unnatural Blocks @@ -422,12 +422,12 @@ public class HerbalismManager extends SkillManager { */ //If its a Crop we need to reward XP when its fully grown - if(isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { + if (isAgeableAndFullyMature(plantData) && !isBizarreAgeable(plantData)) { xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); } //Mark it as natural again as it is being broken - mcMMO.getPlaceStore().setFalse(brokenBlockNewState); + mcMMO.getUserBlockTracker().setEligible(brokenBlockNewState); } else { /* * @@ -437,9 +437,9 @@ public class HerbalismManager extends SkillManager { */ //Calculate XP - if(plantData instanceof Ageable plantAgeable) { + if (plantData instanceof Ageable plantAgeable) { - if(isAgeableMature(plantAgeable) || isBizarreAgeable(plantData)) { + if (isAgeableMature(plantAgeable) || isBizarreAgeable(plantData)) { xpToReward += ExperienceConfig.getInstance().getXp(PrimarySkillType.HERBALISM, brokenBlockNewState.getType()); } @@ -449,12 +449,12 @@ public class HerbalismManager extends SkillManager { } } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Plants processed: "+brokenPlants.size()); } //Reward XP - if(xpToReward > 0) { + if (xpToReward > 0) { applyXpGain(xpToReward, XPGainReason.PVE, XPGainSource.SELF); } } @@ -480,18 +480,18 @@ public class HerbalismManager extends SkillManager { BlockState brokenBlockNewState = blockSnapshot.getBlockRef().getState(); //Remove metadata from the snapshot of blocks - if(brokenBlockNewState.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { + if (brokenBlockNewState.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) { brokenBlockNewState.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, mcMMO.p); } //If the block is not AIR that means it wasn't broken - if(brokenBlockNewState.getType() != Material.AIR) { + if (brokenBlockNewState.getType() != Material.AIR) { continue; } - if(mcMMO.getPlaceStore().isTrue(brokenBlockNewState)) { + if (mcMMO.getUserBlockTracker().isIneligible(brokenBlockNewState)) { //Mark it as natural again as it is being broken - mcMMO.getPlaceStore().setFalse(brokenBlockNewState); + mcMMO.getUserBlockTracker().setEligible(brokenBlockNewState); } else { //TODO: Do we care about chorus flower age? //Calculate XP for the old type @@ -500,13 +500,13 @@ public class HerbalismManager extends SkillManager { } } - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Chorus Plants checked for XP: "+brokenPlants.size()); mmoPlayer.getPlayer().sendMessage("Valid Chorus Plant XP Gains: "+blocksGivingXP); } //Reward XP - if(xpToReward > 0) { + if (xpToReward > 0) { applyXpGain(xpToReward, XPGainReason.PVE, XPGainSource.SELF); } } @@ -525,7 +525,7 @@ public class HerbalismManager extends SkillManager { //Add the initial block blocksBroken.add(originBlockState.getBlock()); - if(!isOneBlockPlant(originBlockMaterial)) { + if (!isOneBlockPlant(originBlockMaterial)) { //If the block is a multi-block structure, capture a set of all blocks broken and return that blocksBroken = getBrokenBlocksMultiBlockPlants(originBlockState); } @@ -602,7 +602,7 @@ public class HerbalismManager extends SkillManager { Block block = originBlock.getBlock(); //Add the initial block to the set - if(inclusive) + if (inclusive) brokenBlocks.add(block); //Limit our search @@ -637,12 +637,13 @@ public class HerbalismManager extends SkillManager { /** * Check for success on herbalism double drops + * * @param blockState target block state - * @return true if double drop succeeds + * @return true if the double drop succeeds */ - private boolean checkDoubleDrop(BlockState blockState) - { - return BlockUtils.checkDoubleDrops(getPlayer(), blockState, skill, SubSkillType.HERBALISM_DOUBLE_DROPS); + private boolean checkDoubleDrop(@NotNull BlockState blockState) { + requireNonNull(blockState, "BlockState cannot be null"); + return BlockUtils.checkDoubleDrops(mmoPlayer, blockState, SubSkillType.HERBALISM_DOUBLE_DROPS); } /** @@ -652,7 +653,7 @@ public class HerbalismManager extends SkillManager { * @return true if the ability was successful, false otherwise */ public boolean processGreenThumbBlocks(BlockState blockState) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, mmoPlayer)) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.GTh.Fail"); return false; } @@ -667,7 +668,7 @@ public class HerbalismManager extends SkillManager { * @return true if the ability was successful, false otherwise */ public boolean processHylianLuck(BlockState blockState) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_HYLIAN_LUCK, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_HYLIAN_LUCK, mmoPlayer)) { return false; } @@ -676,7 +677,6 @@ public class HerbalismManager extends SkillManager { return false; List treasures = TreasureConfig.getInstance().hylianMap.get(friendly); - Player player = getPlayer(); if (treasures.isEmpty()) { return false; @@ -686,13 +686,13 @@ public class HerbalismManager extends SkillManager { for (HylianTreasure treasure : treasures) { if (skillLevel >= treasure.getDropLevel() - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.HERBALISM, player, treasure.getDropChance())) { - if (!EventUtils.simulateBlockBreak(blockState.getBlock(), player)) { + && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.HERBALISM, mmoPlayer, treasure.getDropChance())) { + if (!EventUtils.simulateBlockBreak(blockState.getBlock(), mmoPlayer.getPlayer())) { return false; } blockState.setType(Material.AIR); Misc.spawnItem(getPlayer(), location, treasure.getDrop(), ItemSpawnReason.HYLIAN_LUCK_TREASURE); - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE, "Herbalism.HylianLuck"); + NotificationManager.sendPlayerInformation(mmoPlayer.getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Herbalism.HylianLuck"); return true; } } @@ -706,25 +706,24 @@ public class HerbalismManager extends SkillManager { * @return true if the ability was successful, false otherwise */ public boolean processShroomThumb(BlockState blockState) { - Player player = getPlayer(); - PlayerInventory playerInventory = player.getInventory(); + PlayerInventory playerInventory = getPlayer().getInventory(); if (!playerInventory.contains(Material.BROWN_MUSHROOM, 1)) { - NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.BROWN_MUSHROOM)); + NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.BROWN_MUSHROOM)); return false; } if (!playerInventory.contains(Material.RED_MUSHROOM, 1)) { - NotificationManager.sendPlayerInformation(player, NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.RED_MUSHROOM)); + NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.REQUIREMENTS_NOT_MET, "Skills.NeedMore", StringUtils.getPrettyItemString(Material.RED_MUSHROOM)); return false; } playerInventory.removeItem(new ItemStack(Material.BROWN_MUSHROOM)); playerInventory.removeItem(new ItemStack(Material.RED_MUSHROOM)); - player.updateInventory(); + getPlayer().updateInventory(); - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_SHROOM_THUMB, player)) { - NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.ShroomThumb.Fail"); + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_SHROOM_THUMB, mmoPlayer)) { + NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE_FAILED, "Herbalism.Ability.ShroomThumb.Fail"); return false; } @@ -789,7 +788,7 @@ public class HerbalismManager extends SkillManager { return false; } - if (!greenTerra && !ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, player)) { + if (!greenTerra && !ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.HERBALISM_GREEN_THUMB, mmoPlayer)) { return false; } @@ -797,7 +796,7 @@ public class HerbalismManager extends SkillManager { return false; } - if(EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, blockState.getBlock()) + if (EventUtils.callSubSkillBlockEvent(player, SubSkillType.HERBALISM_GREEN_THUMB, blockState.getBlock()) .isCancelled()) { return false; } else { @@ -816,7 +815,7 @@ public class HerbalismManager extends SkillManager { private boolean processGrowingPlants(BlockState blockState, Ageable ageable, BlockBreakEvent blockBreakEvent, boolean greenTerra) { //This check is needed - if(isBizarreAgeable(ageable)) { + if (isBizarreAgeable(ageable)) { return false; } @@ -824,7 +823,7 @@ public class HerbalismManager extends SkillManager { int greenThumbStage = getGreenThumbStage(greenTerra); //Immature plants will start over at 0 - if(!isAgeableMature(ageable)) { + if (!isAgeableMature(ageable)) { // blockBreakEvent.setCancelled(true); startReplantTask(0, blockBreakEvent, blockState, true); // blockState.setType(Material.AIR); @@ -846,11 +845,9 @@ public class HerbalismManager extends SkillManager { if (greenTerra || greenThumbStage > 2) { finalAge = 2; - } - else if (greenThumbStage == 2) { + } else if (greenThumbStage == 2) { finalAge = 1; - } - else { + } else { finalAge = 0; } break; @@ -859,8 +856,7 @@ public class HerbalismManager extends SkillManager { if (getGreenThumbStage(greenTerra) >= 2) { finalAge = 1; - } - else { + } else { finalAge = 0; } break; @@ -876,7 +872,7 @@ public class HerbalismManager extends SkillManager { } private int getGreenThumbStage(boolean greenTerraActive) { - if(greenTerraActive) + if (greenTerraActive) return Math.min(RankUtils.getHighestRank(SubSkillType.HERBALISM_GREEN_THUMB), RankUtils.getRank(getPlayer(), SubSkillType.HERBALISM_GREEN_THUMB) + 1); diff --git a/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java new file mode 100644 index 000000000..d309ad9cb --- /dev/null +++ b/src/main/java/com/gmail/nossr50/skills/maces/MacesManager.java @@ -0,0 +1,11 @@ +package com.gmail.nossr50.skills.maces; + +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.skills.SkillManager; + +public class MacesManager extends SkillManager { + public MacesManager(McMMOPlayer mmoPlayer) { + super(mmoPlayer, PrimarySkillType.MACES); + } +} diff --git a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java index 98b8cf8b6..76cf6f8c6 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/BlastMining.java @@ -62,9 +62,8 @@ public class BlastMining { return tier == Tier.EIGHT ? tier.getLevel() : tierList.get(tierList.indexOf(tier) - 1).getLevel(); }*/ - for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) - { - if(getBlastDamageDecrease(i+1) > 0) + for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) { + if (getBlastDamageDecrease(i+1) > 0) return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); } @@ -81,9 +80,8 @@ public class BlastMining { return tier == Tier.EIGHT ? tier.getLevel() : tierList.get(tierList.indexOf(tier) - 1).getLevel(); }*/ - for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) - { - if(getBlastRadiusModifier(i+1) > 0) + for(int i = 0; i < SubSkillType.MINING_BLAST_MINING.getNumRanks()-1; i++) { + if (getBlastRadiusModifier(i+1) > 0) return RankUtils.getRankUnlockLevel(SubSkillType.MINING_BLAST_MINING, i+1); } @@ -102,8 +100,7 @@ public class BlastMining { return false; } - if(UserManager.getPlayer(defender) == null) - { + if (UserManager.getPlayer(defender) == null) { return false; } diff --git a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java index b91274ce4..3bb866cdd 100644 --- a/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java +++ b/src/main/java/com/gmail/nossr50/skills/mining/MiningManager.java @@ -13,10 +13,11 @@ import com.gmail.nossr50.runnables.skills.AbilityCooldownTask; import com.gmail.nossr50.skills.SkillManager; import com.gmail.nossr50.util.*; import com.gmail.nossr50.util.player.NotificationManager; +import com.gmail.nossr50.util.random.Probability; import com.gmail.nossr50.util.random.ProbabilityUtil; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillUtils; -import org.apache.commons.lang.math.RandomUtils; +import org.apache.commons.lang3.RandomUtils; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockState; @@ -40,7 +41,7 @@ public class MiningManager extends SkillManager { } public boolean canUseDemolitionsExpertise() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_DEMOLITIONS_EXPERTISE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_DEMOLITIONS_EXPERTISE)) return false; return getSkillLevel() >= BlastMining.getDemolitionExpertUnlockLevel() && Permissions.demolitionsExpertise(getPlayer()); @@ -60,7 +61,7 @@ public class MiningManager extends SkillManager { } public boolean canUseBiggerBombs() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_BIGGER_BOMBS)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.MINING_BIGGER_BOMBS)) return false; return getSkillLevel() >= BlastMining.getBiggerBombsUnlockLevel() && Permissions.biggerBombs(getPlayer()); @@ -93,18 +94,18 @@ public class MiningManager extends SkillManager { SkillUtils.handleDurabilityChange(getPlayer().getInventory().getItemInMainHand(), mcMMO.p.getGeneralConfig().getAbilityToolDamage()); } - if(!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, blockState.getType()) || !canDoubleDrop()) + if (!mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.MINING, blockState.getType()) || !canDoubleDrop()) return; boolean silkTouch = player.getInventory().getItemInMainHand().containsEnchantment(Enchantment.SILK_TOUCH); - if(silkTouch && !mcMMO.p.getAdvancedConfig().getDoubleDropSilkTouchEnabled()) + if (silkTouch && !mcMMO.p.getAdvancedConfig().getDoubleDropSilkTouchEnabled()) return; //Mining mastery allows for a chance of triple drops - if(canMotherLode()) { + if (canMotherLode()) { //Triple Drops failed so do a normal double drops check - if(!processTripleDrops(blockState)) { + if (!processTripleDrops(blockState)) { processDoubleDrops(blockState); } } else { @@ -115,7 +116,7 @@ public class MiningManager extends SkillManager { private boolean processTripleDrops(@NotNull BlockState blockState) { //TODO: Make this readable - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_MOTHER_LODE, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_MOTHER_LODE, mmoPlayer)) { BlockUtils.markDropsAsBonus(blockState, 2); return true; } else { @@ -125,7 +126,7 @@ public class MiningManager extends SkillManager { private void processDoubleDrops(@NotNull BlockState blockState) { //TODO: Make this readable - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_DOUBLE_DROPS, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.MINING_DOUBLE_DROPS, mmoPlayer)) { boolean useTriple = mmoPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) && mcMMO.p.getAdvancedConfig().getAllowMiningTripleDrops(); BlockUtils.markDropsAsBonus(blockState, useTriple); } @@ -181,8 +182,8 @@ public class MiningManager extends SkillManager { //Containers usually have 0 XP unless someone edited their config in a very strange way if (ExperienceConfig.getInstance().getXp(PrimarySkillType.MINING, targetBlock) != 0 && !(targetBlock instanceof Container) - && !mcMMO.getPlaceStore().isTrue(targetBlock)) { - if(BlockUtils.isOre(blockState)) { + && !mcMMO.getUserBlockTracker().isIneligible(targetBlock)) { + if (BlockUtils.isOre(blockState)) { ores.add(blockState); } else { notOres.add(blockState); @@ -199,16 +200,16 @@ public class MiningManager extends SkillManager { //Drop "debris" based on skill modifiers for(BlockState blockState : notOres) { - if(isDropIllegal(blockState.getType())) + if (isDropIllegal(blockState.getType())) continue; - if(RandomUtils.nextFloat() < debrisYield) { + if (Probability.ofPercent(50).evaluate()) { Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_DEBRIS_NON_ORES); // Initial block that would have been dropped } } for (BlockState blockState : ores) { - if(isDropIllegal(blockState.getType())) + if (isDropIllegal(blockState.getType())) continue; if (RandomUtils.nextFloat() < (yield + oreBonus)) { @@ -216,7 +217,7 @@ public class MiningManager extends SkillManager { Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_ORES); // Initial block that would have been dropped - if (mcMMO.p.getAdvancedConfig().isBlastMiningBonusDropsEnabled() && !mcMMO.getPlaceStore().isTrue(blockState)) { + if (mcMMO.p.getAdvancedConfig().isBlastMiningBonusDropsEnabled() && !mcMMO.getUserBlockTracker().isIneligible(blockState)) { for (int i = 1; i < dropMultiplier; i++) { // Bukkit.broadcastMessage("Bonus Drop on Ore: "+blockState.getType().toString()); Misc.spawnItem(getPlayer(), Misc.getBlockCenter(blockState), new ItemStack(blockState.getType()), ItemSpawnReason.BLAST_MINING_ORES_BONUS_DROP); // Initial block that would have been dropped diff --git a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java index 08a6ce8e8..0e022ec86 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/RepairManager.java @@ -66,8 +66,8 @@ public class RepairManager extends SkillManager { Player player = getPlayer(); Repairable repairable = mcMMO.getRepairableManager().getRepairable(item.getType()); if (item.getItemMeta() != null) { - if(item.getItemMeta().hasCustomModelData()) { - if(!mcMMO.p.getCustomItemSupportConfig().isCustomRepairAllowed()) { + if (item.getItemMeta().hasCustomModelData()) { + if (!mcMMO.p.getCustomItemSupportConfig().isCustomRepairAllowed()) { NotificationManager.sendPlayerInformation(player, NotificationType.SUBSKILL_MESSAGE_FAILED, "Anvil.Repair.Reject.CustomModelData"); return; @@ -326,10 +326,10 @@ public class RepairManager extends SkillManager { * @return true if bonus granted, false otherwise */ private boolean checkPlayerProcRepair() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.REPAIR_SUPER_REPAIR)) return false; - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.REPAIR_SUPER_REPAIR, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.REPAIR_SUPER_REPAIR, mmoPlayer)) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Repair.Skills.FeltEasy"); return true; } @@ -370,8 +370,8 @@ public class RepairManager extends SkillManager { for (Entry enchant : enchants.entrySet()) { int enchantLevel = enchant.getValue(); - if(!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { - if(enchantLevel > enchant.getKey().getMaxLevel()) { + if (!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { + if (enchantLevel > enchant.getKey().getMaxLevel()) { enchantLevel = enchant.getKey().getMaxLevel(); item.addEnchantment(enchant.getKey(), enchantLevel); @@ -380,15 +380,14 @@ public class RepairManager extends SkillManager { Enchantment enchantment = enchant.getKey(); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, getPlayer(), getKeepEnchantChance())) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, getKeepEnchantChance())) { if (ArcaneForging.arcaneForgingDowngrades && enchantLevel > 1 - && (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, getPlayer(), 100 - getDowngradeEnchantChance()))) { + && (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.REPAIR, mmoPlayer, 100 - getDowngradeEnchantChance()))) { item.addUnsafeEnchantment(enchantment, enchantLevel - 1); downgraded = true; } - } - else { + } else { item.removeEnchantment(enchantment); } } @@ -397,11 +396,9 @@ public class RepairManager extends SkillManager { if (newEnchants.isEmpty()) { NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Fail"); - } - else if (downgraded || newEnchants.size() < enchants.size()) { + } else if (downgraded || newEnchants.size() < enchants.size()) { NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Downgrade"); - } - else { + } else { NotificationManager.sendPlayerInformationChatOnly(getPlayer(), "Repair.Arcane.Perfect"); } } diff --git a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java index de201456d..2849c9dae 100644 --- a/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java +++ b/src/main/java/com/gmail/nossr50/skills/repair/repairables/SimpleRepairable.java @@ -67,7 +67,7 @@ public class SimpleRepairable implements Repairable { @Override public int getMinimumQuantity() { - if(minQuantity == -1) + if (minQuantity == -1) return Math.max(SkillUtils.getRepairAndSalvageQuantities(itemMaterial, repairMaterial), 1); else return minQuantity; diff --git a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java index cffd2bf37..b80160c89 100644 --- a/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java +++ b/src/main/java/com/gmail/nossr50/skills/salvage/SalvageManager.java @@ -125,7 +125,7 @@ public class SalvageManager extends SkillManager { for(int x = 0; x < potentialSalvageYield-1; x++) { - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, player, chanceOfSuccess)) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, mmoPlayer, chanceOfSuccess)) { chanceOfSuccess-=3; chanceOfSuccess = Math.max(chanceOfSuccess, 90); @@ -196,7 +196,7 @@ public class SalvageManager extends SkillManager { } public double getExtractFullEnchantChance() { - if(Permissions.hasSalvageEnchantBypassPerk(getPlayer())) + if (Permissions.hasSalvageEnchantBypassPerk(getPlayer())) return 100.0D; return mcMMO.p.getAdvancedConfig().getArcaneSalvageExtractFullEnchantsChance(getArcaneSalvageRank()); @@ -224,20 +224,21 @@ public class SalvageManager extends SkillManager { int enchantLevel = enchant.getValue(); - if(!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { - if(enchantLevel > enchant.getKey().getMaxLevel()) { + if (!ExperienceConfig.getInstance().allowUnsafeEnchantments()) { + if (enchantLevel > enchant.getKey().getMaxLevel()) { enchantLevel = enchant.getKey().getMaxLevel(); } } if (!Salvage.arcaneSalvageEnchantLoss || Permissions.hasSalvageEnchantBypassPerk(player) - || ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, player, getExtractFullEnchantChance())) { + || ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.SALVAGE, mmoPlayer, getExtractFullEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel, true); - } - else if (enchantLevel > 1 + } else if (enchantLevel > 1 && Salvage.arcaneSalvageDowngrades - && ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SALVAGE, player, getExtractPartialEnchantChance())) { + && ProbabilityUtil.isStaticSkillRNGSuccessful( + PrimarySkillType.SALVAGE, mmoPlayer, getExtractPartialEnchantChance())) { enchantMeta.addStoredEnchant(enchant.getKey(), enchantLevel - 1, true); downgraded = true; } else { @@ -245,12 +246,10 @@ public class SalvageManager extends SkillManager { } } - if(failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) - { + if (failedAllEnchants(arcaneFailureCount, enchants.entrySet().size())) { NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcaneFailed"); return null; - } else if(downgraded) - { + } else if (downgraded) { NotificationManager.sendPlayerInformationChatOnly(player, "Salvage.Skills.ArcanePartial"); } diff --git a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java index 9bb4a6e39..f8c43c0ca 100644 --- a/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/smelting/SmeltingManager.java @@ -24,7 +24,7 @@ public class SmeltingManager extends SkillManager { public boolean isSecondSmeltSuccessful() { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SMELTING_SECOND_SMELT) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SMELTING_SECOND_SMELT, getPlayer()); + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SMELTING_SECOND_SMELT, mmoPlayer); } /** @@ -36,8 +36,7 @@ public class SmeltingManager extends SkillManager { return Math.min(Short.MAX_VALUE, Math.max(1, burnTime * getFuelEfficiencyMultiplier())); } - public int getFuelEfficiencyMultiplier() - { + public int getFuelEfficiencyMultiplier() { return switch (RankUtils.getRank(getPlayer(), SubSkillType.SMELTING_FUEL_EFFICIENCY)) { case 1 -> 2; case 2 -> 3; @@ -73,7 +72,7 @@ public class SmeltingManager extends SkillManager { FurnaceInventory furnaceInventory = furnace.getInventory(); ItemStack furnaceResult = furnaceInventory.getResult(); - if(furnaceResult == null) + if (furnaceResult == null) return true; //This actually means there is nothing yet in the resulting item slot, which means it should always be okay to double smelt int resultAmount = furnaceResult.getAmount(); //Amount before double smelt diff --git a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java index d68d98e8d..48957df91 100644 --- a/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/swords/SwordsManager.java @@ -41,14 +41,14 @@ public class SwordsManager extends SkillManager { } public boolean canUseCounterAttack(Entity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK)) return false; return target instanceof LivingEntity && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.SWORDS_COUNTER_ATTACK); } public boolean canUseSerratedStrike() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_SERRATED_STRIKES)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.SWORDS_SERRATED_STRIKES)) return false; return mmoPlayer.getAbilityMode(SuperAbilityType.SERRATED_STRIKES); @@ -60,13 +60,13 @@ public class SwordsManager extends SkillManager { * @param target The defending entity */ public void processRupture(@NotNull LivingEntity target) { - if(!canUseRupture()) + if (!canUseRupture()) return; - if(target.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { + if (target.hasMetadata(MetadataConstants.METADATA_KEY_RUPTURE)) { RuptureTaskMeta ruptureTaskMeta = (RuptureTaskMeta) target.getMetadata(MetadataConstants.METADATA_KEY_RUPTURE).get(0); - if(mmoPlayer.isDebugMode()) { + if (mmoPlayer.isDebugMode()) { mmoPlayer.getPlayer().sendMessage("Rupture task ongoing for target " + target.toString()); mmoPlayer.getPlayer().sendMessage(ruptureTaskMeta.getRuptureTimerTask().toString()); } @@ -76,12 +76,12 @@ public class SwordsManager extends SkillManager { } double ruptureOdds = mcMMO.p.getAdvancedConfig().getRuptureChanceToApplyOnHit(getRuptureRank()); - if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SWORDS, this.getPlayer(), ruptureOdds)) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.SWORDS, mmoPlayer, ruptureOdds)) { if (target instanceof Player defender) { //Don't start or add to a bleed if they are blocking - if(defender.isBlocking()) + if (defender.isBlocking()) return; if (NotificationManager.doesPlayerUseNotifications(defender)) { @@ -108,27 +108,24 @@ public class SwordsManager extends SkillManager { return RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_RUPTURE); } - public double getStabDamage() - { + public double getStabDamage() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.SWORDS_STAB); - if(rank > 0) - { + if (rank > 0) { return (1.0D + (rank * 1.5)); } return 0; } - public int getToolTier(@NotNull ItemStack itemStack) - { - if(ItemUtils.isNetheriteTool(itemStack)) + public int getToolTier(@NotNull ItemStack itemStack) { + if (ItemUtils.isNetheriteTool(itemStack)) return 5; - if(ItemUtils.isDiamondTool(itemStack)) + if (ItemUtils.isDiamondTool(itemStack)) return 4; - else if(ItemUtils.isIronTool(itemStack) || ItemUtils.isGoldTool(itemStack)) + else if (ItemUtils.isIronTool(itemStack) || ItemUtils.isGoldTool(itemStack)) return 3; - else if(ItemUtils.isStoneTool(itemStack)) + else if (ItemUtils.isStoneTool(itemStack)) return 2; else return 1; @@ -142,7 +139,7 @@ public class SwordsManager extends SkillManager { */ public void counterAttackChecks(@NotNull LivingEntity attacker, double damage) { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SWORDS_COUNTER_ATTACK, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.SWORDS_COUNTER_ATTACK, mmoPlayer)) { CombatUtils.dealDamage(attacker, damage / Swords.counterAttackModifier, getPlayer()); NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Swords.Combat.Countered"); diff --git a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java index dcee2e0bd..42ed59a9e 100644 --- a/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/taming/TamingManager.java @@ -31,6 +31,8 @@ import org.jetbrains.annotations.NotNull; import java.util.HashMap; +import static com.gmail.nossr50.util.MobMetadataUtils.flagMetadata; + public class TamingManager extends SkillManager { //TODO: Temporary static cache, will be changed in 2.2 private static HashMap summoningItems; @@ -57,7 +59,7 @@ public class TamingManager extends SkillManager { private void initStaticCaches() { //TODO: Temporary static cache, will be changed in 2.2 //This is shared between instances of TamingManager - if(summoningItems == null) { + if (summoningItems == null) { summoningItems = new HashMap<>(); summoningItems.put(mcMMO.p.getGeneralConfig().getTamingCOTWMaterial(CallOfTheWildType.CAT.getConfigEntityTypeEntry()), CallOfTheWildType.CAT); @@ -67,7 +69,7 @@ public class TamingManager extends SkillManager { //TODO: Temporary static cache, will be changed in 2.2 //This is shared between instances of TamingManager - if(cotwSummonDataProperties == null) { + if (cotwSummonDataProperties == null) { cotwSummonDataProperties = new HashMap<>(); for(CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) { @@ -114,14 +116,14 @@ public class TamingManager extends SkillManager { } public boolean canUseGore() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_GORE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_GORE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_GORE); } public boolean canUseBeastLore() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_BEAST_LORE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_BEAST_LORE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.TAMING_BEAST_LORE); @@ -143,7 +145,7 @@ public class TamingManager extends SkillManager { * @param damage The damage being absorbed by the wolf */ public void fastFoodService(@NotNull Wolf wolf, double damage) { - if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.TAMING_FAST_FOOD_SERVICE, getPlayer())) { + if (!ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.TAMING_FAST_FOOD_SERVICE, mmoPlayer)) { return; } @@ -176,7 +178,7 @@ public class TamingManager extends SkillManager { * Summon an ocelot to your side. */ public void summonOcelot() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.OCELOT)) { @@ -190,7 +192,7 @@ public class TamingManager extends SkillManager { * Summon a wolf to your side. */ public void summonWolf() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.WOLF)) { @@ -204,7 +206,7 @@ public class TamingManager extends SkillManager { * Summon a horse to your side. */ public void summonHorse() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_CALL_OF_THE_WILD)) return; if (!Permissions.callOfTheWild(getPlayer(), EntityType.HORSE)) { @@ -233,9 +235,9 @@ public class TamingManager extends SkillManager { // Bred mules & donkeys can actually have horse-like stats, but llamas cannot. if (beast instanceof AbstractHorse horseLikeCreature && !(beast instanceof Llama)) { - AttributeInstance jumpAttribute = horseLikeCreature.getAttribute(Attribute.HORSE_JUMP_STRENGTH); + AttributeInstance jumpAttribute = horseLikeCreature.getAttribute(mcMMO.p.getAttributeMapper().getHorseJumpStrength()); - if(jumpAttribute != null) { + if (jumpAttribute != null) { double jumpStrength = jumpAttribute.getValue(); // Taken from https://minecraft.wiki/w/Horse#Jump_strength jumpStrength = -0.1817584952 * Math.pow(jumpStrength, 3) + 3.689713992 * Math.pow(jumpStrength, 2) + 2.128599134 * jumpStrength - 0.343930367; @@ -259,10 +261,10 @@ public class TamingManager extends SkillManager { } public void pummel(LivingEntity target, Wolf wolf) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.TAMING_PUMMEL)) return; - if(!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, getPlayer(), mcMMO.p.getAdvancedConfig().getPummelChance())) + if (!ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.TAMING, mmoPlayer, mcMMO.p.getAdvancedConfig().getPummelChance())) return; ParticleEffectUtils.playGreaterImpactEffect(target); @@ -277,10 +279,8 @@ public class TamingManager extends SkillManager { } public void attackTarget(LivingEntity target) { - if(target instanceof Tameable tameable) - { - if(tameable.getOwner() == getPlayer()) - { + if (target instanceof Tameable tameable) { + if (tameable.getOwner() == getPlayer()) { return; } } @@ -305,7 +305,7 @@ public class TamingManager extends SkillManager { private void processCallOfTheWild() { //Prevent summoning too many things accidentally if a player holds down the button - if(lastSummonTimeStamp + 150 > System.currentTimeMillis()) { + if (lastSummonTimeStamp + 150 > System.currentTimeMillis()) { return; } else { lastSummonTimeStamp = System.currentTimeMillis(); @@ -315,7 +315,7 @@ public class TamingManager extends SkillManager { ItemStack itemInMainHand = player.getInventory().getItemInMainHand(); //Check if the item the player is currently holding is a COTW item - if(isCOTWItem(itemInMainHand)) { + if (isCOTWItem(itemInMainHand)) { //Get the summoning type CallOfTheWildType callOfTheWildType = summoningItems.get(itemInMainHand.getType()); TamingSummon tamingSummon = cotwSummonDataProperties.get(callOfTheWildType); @@ -324,7 +324,7 @@ public class TamingManager extends SkillManager { int amountSummoned = 0; //Check to see if players have the correct amount of the item required to summon - if(itemInMainHand.getAmount() >= tamingSummon.getItemAmountRequired()) { + if (itemInMainHand.getAmount() >= tamingSummon.getItemAmountRequired()) { //Initial Spawn location Location spawnLocation = Misc.getLocationOffset(player.getLocation(), 1); @@ -356,7 +356,7 @@ public class TamingManager extends SkillManager { } //Remove items from the player if they had at least one entity summoned successfully - if(amountSummoned >= 1) { + if (amountSummoned >= 1) { //Remove the items used to summon int itemAmountAfterPayingCost = itemInMainHand.getAmount() - tamingSummon.getItemAmountRequired(); itemInMainHand.setAmount(itemAmountAfterPayingCost); @@ -410,11 +410,11 @@ public class TamingManager extends SkillManager { addToTracker(callOfWildEntity, CallOfTheWildType.CAT); //Randomize the cat - if(callOfWildEntity instanceof Ocelot) { + if (callOfWildEntity instanceof Ocelot) { int numberOfTypes = Ocelot.Type.values().length; ((Ocelot) callOfWildEntity).setCatType(Ocelot.Type.values()[Misc.getRandom().nextInt(numberOfTypes)]); ((Ocelot) callOfWildEntity).setAdult(); - } else if(callOfWildEntity instanceof Cat) { + } else if (callOfWildEntity instanceof Cat) { int numberOfTypes = Cat.Type.values().length; ((Cat) callOfWildEntity).setCatType(Cat.Type.values()[Misc.getRandom().nextInt(numberOfTypes)]); ((Cat) callOfWildEntity).setAdult(); @@ -459,7 +459,7 @@ public class TamingManager extends SkillManager { private void applyMetaDataToCOTWEntity(LivingEntity summonedEntity) { //This helps identify the entity as being summoned by COTW - mcMMO.getMetadataService().getMobMetadataService().flagMetadata(MobMetaFlagType.COTW_SUMMONED_MOB, summonedEntity); + flagMetadata(MobMetaFlagType.COTW_SUMMONED_MOB, summonedEntity); } /** diff --git a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java index bd4296d0f..fcacc014c 100644 --- a/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java +++ b/src/main/java/com/gmail/nossr50/skills/tridents/TridentsManager.java @@ -3,9 +3,7 @@ package com.gmail.nossr50.skills.tridents; import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; -import com.gmail.nossr50.datatypes.skills.ToolType; import com.gmail.nossr50.skills.SkillManager; -import com.gmail.nossr50.util.Permissions; import com.gmail.nossr50.util.skills.RankUtils; public class TridentsManager extends SkillManager { @@ -13,20 +11,12 @@ public class TridentsManager extends SkillManager { super(mmoPlayer, PrimarySkillType.TRIDENTS); } - /** - * Checks if the player can activate the Super Ability for Tridents - * @return true if the player can activate the Super Ability, false otherwise - */ - public boolean canActivateAbility() { - return mmoPlayer.getToolPreparationMode(ToolType.TRIDENTS) && Permissions.tridentsSuper(getPlayer()); - } - public double impaleDamageBonus() { int rank = RankUtils.getRank(getPlayer(), SubSkillType.TRIDENTS_IMPALE); - if(rank > 1) { + if (rank > 1) { return (1.0D + (rank * .5D)); - } else if(rank == 1) { + } else if (rank == 1) { return 1.0D; } diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java index cb1124dd4..2e759f7df 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/Unarmed.java @@ -19,27 +19,22 @@ public class Unarmed { int amount = itemDrop.getAmount(); boolean grabbedItem = false; - for(int i = 0; i <= storageContents.length-1; i++) - { - if(amount <= 0) + for(int i = 0; i <= storageContents.length-1; i++) { + if (amount <= 0) break; - if(i == heldItemSlotID) + if (i == heldItemSlotID) continue; //EMPTY SLOT! - if(storageContents[i] == null) - { + if (storageContents[i] == null) { player.getInventory().setItem(i, itemDrop); amount = 0; grabbedItem = true; break; - } - else if(itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) - { + } else if (itemDrop.isSimilar(storageContents[i]) && storageContents[i].getAmount() < storageContents[i].getMaxStackSize()) { //If we can fit this whole itemstack into this item - if(amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) - { + if (amount + storageContents[i].getAmount() <= storageContents[i].getMaxStackSize()) { ItemStack modifiedAmount = storageContents[i]; modifiedAmount.setAmount(amount + storageContents[i].getAmount()); @@ -61,15 +56,14 @@ public class Unarmed { } } - if(amount <= 0) + if (amount <= 0) event.getItem().remove(); //Cleanup Item else event.getItem().getItemStack().setAmount(amount); event.setCancelled(true); - if(grabbedItem) - { + if (grabbedItem) { SoundManager.sendSound(player, player.getLocation(), SoundType.POP); player.updateInventory(); } diff --git a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java index dbc8060ef..933dbb8f4 100644 --- a/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java +++ b/src/main/java/com/gmail/nossr50/skills/unarmed/UnarmedManager.java @@ -33,7 +33,7 @@ public class UnarmedManager extends SkillManager { } public boolean canUseSteelArm() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE); @@ -44,14 +44,14 @@ public class UnarmedManager extends SkillManager { } public boolean canDisarm(LivingEntity target) { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_DISARM)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_DISARM)) return false; return target instanceof Player && ((Player) target).getInventory().getItemInMainHand().getType() != Material.AIR && Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_DISARM); } public boolean canDeflect() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_ARROW_DEFLECT)) return false; Player player = getPlayer(); @@ -60,14 +60,14 @@ public class UnarmedManager extends SkillManager { } public boolean canUseBlockCracker() { - if(!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER)) + if (!RankUtils.hasUnlockedSubskill(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER)) return false; return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.UNARMED_BLOCK_CRACKER); } public boolean blockCrackerCheck(@NotNull BlockState blockState) { - if (!ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_BLOCK_CRACKER, getPlayer())) { + if (!ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_BLOCK_CRACKER, mmoPlayer)) { return false; } @@ -98,12 +98,12 @@ public class UnarmedManager extends SkillManager { * @param defender The defending player */ public void disarmCheck(@NotNull Player defender) { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_DISARM, getPlayer()) && !hasIronGrip(defender)) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_DISARM, mmoPlayer) && !hasIronGrip(defender)) { if (EventUtils.callDisarmEvent(defender).isCancelled()) { return; } - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) return; Item item = Misc.spawnItem(getPlayer(), defender.getLocation(), defender.getInventory().getItemInMainHand(), ItemSpawnReason.UNARMED_DISARMED_ITEM); @@ -121,7 +121,7 @@ public class UnarmedManager extends SkillManager { * Check for arrow deflection. */ public boolean deflectCheck() { - if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_ARROW_DEFLECT, getPlayer())) { + if (ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_ARROW_DEFLECT, mmoPlayer)) { NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Combat.ArrowDeflect"); return true; } @@ -144,7 +144,7 @@ public class UnarmedManager extends SkillManager { * Handle the effects of the Iron Arm ability */ public double calculateSteelArmStyleDamage() { - if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_STEEL_ARM_STYLE, getPlayer())) { + if (ProbabilityUtil.isNonRNGSkillActivationSuccessful(SubSkillType.UNARMED_STEEL_ARM_STYLE, mmoPlayer)) { return getSteelArmStyleDamage(); } @@ -156,13 +156,13 @@ public class UnarmedManager extends SkillManager { double bonus = 0; - if(rank >= 18) + if (rank >= 18) bonus = 1 + rank - 18; double finalBonus = bonus + 0.5 + (rank / 2); - if(mcMMO.p.getAdvancedConfig().isSteelArmDamageCustom()) { + if (mcMMO.p.getAdvancedConfig().isSteelArmDamageCustom()) { return mcMMO.p.getAdvancedConfig().getSteelArmOverride(RankUtils.getRank(getPlayer(), SubSkillType.UNARMED_STEEL_ARM_STYLE), finalBonus); } else { return finalBonus; @@ -178,7 +178,7 @@ public class UnarmedManager extends SkillManager { private boolean hasIronGrip(@NotNull Player defender) { if (!Misc.isNPCEntityExcludingVillagers(defender) && Permissions.isSubSkillEnabled(defender, SubSkillType.UNARMED_IRON_GRIP) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_IRON_GRIP, defender)) { + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.UNARMED_IRON_GRIP, UserManager.getPlayer(defender))) { NotificationManager.sendPlayerInformation(defender, NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Defender"); NotificationManager.sendPlayerInformation(getPlayer(), NotificationType.SUBSKILL_MESSAGE, "Unarmed.Ability.IronGrip.Attacker"); diff --git a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java index dd198131e..e9d4623f3 100644 --- a/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java +++ b/src/main/java/com/gmail/nossr50/skills/woodcutting/WoodcuttingManager.java @@ -72,14 +72,14 @@ public class WoodcuttingManager extends SkillManager { private boolean checkHarvestLumberActivation(Material material) { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.hasReachedRank(1, getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_HARVEST_LUMBER, getPlayer()) + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_HARVEST_LUMBER, mmoPlayer) && mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); } private boolean checkCleanCutsActivation(Material material) { return Permissions.isSubSkillEnabled(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) && RankUtils.hasReachedRank(1, getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER) - && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_CLEAN_CUTS, getPlayer()) + && ProbabilityUtil.isSkillRNGSuccessful(SubSkillType.WOODCUTTING_CLEAN_CUTS, mmoPlayer) && mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, material); } @@ -90,22 +90,22 @@ public class WoodcuttingManager extends SkillManager { */ public void processBonusDropCheck(@NotNull BlockState blockState) { //TODO: Why isn't this using the item drop event? Potentially because of Tree Feller? This should be adjusted either way. - if(mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, blockState.getType())) { + if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, blockState.getType())) { //Mastery enabled for player - if(Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_CLEAN_CUTS)) { - if(checkCleanCutsActivation(blockState.getType())) { + if (Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_CLEAN_CUTS)) { + if (checkCleanCutsActivation(blockState.getType())) { //Triple drops spawnHarvestLumberBonusDrops(blockState); spawnHarvestLumberBonusDrops(blockState); } else { //Harvest Lumber Check - if(checkHarvestLumberActivation(blockState.getType())) { + if (checkHarvestLumberActivation(blockState.getType())) { spawnHarvestLumberBonusDrops(blockState); } } //No Mastery (no Clean Cuts) } else if (Permissions.canUseSubSkill(getPlayer(), SubSkillType.WOODCUTTING_HARVEST_LUMBER)) { - if(checkHarvestLumberActivation(blockState.getType())) { + if (checkHarvestLumberActivation(blockState.getType())) { spawnHarvestLumberBonusDrops(blockState); } } @@ -113,7 +113,7 @@ public class WoodcuttingManager extends SkillManager { } public void processWoodcuttingBlockXP(@NotNull BlockState blockState) { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) return; int xp = getExperienceFromLog(blockState); @@ -191,8 +191,7 @@ public class WoodcuttingManager extends SkillManager { return; } } - } - else { + } else { // Cover DOWN processTreeFellerTargetBlock(blockState.getBlock().getRelative(BlockFace.DOWN).getState(), futureCenterBlocks, treeFellerBlocks); // Search in a cube @@ -269,7 +268,7 @@ public class WoodcuttingManager extends SkillManager { * in treeFellerBlocks. */ private boolean processTreeFellerTargetBlock(@NotNull BlockState blockState, @NotNull List futureCenterBlocks, @NotNull Set treeFellerBlocks) { - if (treeFellerBlocks.contains(blockState) || mcMMO.getPlaceStore().isTrue(blockState)) { + if (treeFellerBlocks.contains(blockState) || mcMMO.getUserBlockTracker().isIneligible(blockState)) { return false; } @@ -282,8 +281,7 @@ public class WoodcuttingManager extends SkillManager { treeFellerBlocks.add(blockState); futureCenterBlocks.add(blockState); return true; - } - else if (BlockUtils.isNonWoodPartOfTree(blockState)) { + } else if (BlockUtils.isNonWoodPartOfTree(blockState)) { treeFellerBlocks.add(blockState); return false; } @@ -323,16 +321,20 @@ public class WoodcuttingManager extends SkillManager { //Bonus Drops / Harvest lumber checks processBonusDropCheck(blockState); } else if (BlockUtils.isNonWoodPartOfTree(blockState)) { - // 90% of the time do not drop leaf blocks - if (ThreadLocalRandom.current().nextInt(100) > 90) { - Misc.spawnItemsFromCollection(getPlayer(), Misc.getBlockCenter(blockState), block.getDrops(itemStack), ItemSpawnReason.TREE_FELLER_DISPLACED_BLOCK); + // 75% of the time do not drop leaf blocks + if (blockState.getType().getKey().getKey().toLowerCase().contains("sapling") + || ThreadLocalRandom.current().nextInt(100) > 75) { + Misc.spawnItemsFromCollection(getPlayer(), + Misc.getBlockCenter(blockState), + block.getDrops(itemStack), + ItemSpawnReason.TREE_FELLER_DISPLACED_BLOCK); } //Drop displaced non-woodcutting XP blocks - if(RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { - if(RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { - if(mcMMO.p.getAdvancedConfig().isKnockOnWoodXPOrbEnabled()) { - if(ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, player, 10)) { + if (RankUtils.hasUnlockedSubskill(player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (RankUtils.hasReachedRank(2, player, SubSkillType.WOODCUTTING_KNOCK_ON_WOOD)) { + if (mcMMO.p.getAdvancedConfig().isKnockOnWoodXPOrbEnabled()) { + if (ProbabilityUtil.isStaticSkillRNGSuccessful(PrimarySkillType.WOODCUTTING, mmoPlayer, 10)) { int randOrbCount = Math.max(1, Misc.getRandom().nextInt(100)); Misc.spawnExperienceOrb(blockState.getLocation(), randOrbCount); } @@ -352,7 +354,7 @@ public class WoodcuttingManager extends SkillManager { } private int updateProcessedLogCount(int xp, int processedLogCount, int beforeXP) { - if(beforeXP != xp) + if (beforeXP != xp) processedLogCount+=1; return processedLogCount; @@ -369,15 +371,15 @@ public class WoodcuttingManager extends SkillManager { * @return Amount of experience */ private static int processTreeFellerXPGains(BlockState blockState, int woodCount) { - if(mcMMO.getPlaceStore().isTrue(blockState)) + if (mcMMO.getUserBlockTracker().isIneligible(blockState)) return 0; int rawXP = ExperienceConfig.getInstance().getXp(PrimarySkillType.WOODCUTTING, blockState.getType()); - if(rawXP <= 0) + if (rawXP <= 0) return 0; - if(ExperienceConfig.getInstance().isTreeFellerXPReduced()) { + if (ExperienceConfig.getInstance().isTreeFellerXPReduced()) { int reducedXP = rawXP - (woodCount * 5); rawXP = Math.max(1, reducedXP); return rawXP; diff --git a/src/main/java/com/gmail/nossr50/util/AttributeMapper.java b/src/main/java/com/gmail/nossr50/util/AttributeMapper.java new file mode 100644 index 000000000..2d15d55bd --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/AttributeMapper.java @@ -0,0 +1,45 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.Registry; +import org.bukkit.attribute.Attribute; + +public class AttributeMapper { + private final mcMMO pluginRef; + private static final String GENERIC_JUMP_STRENGTH = "generic.jump_strength"; + private static final String HORSE_JUMP_STRENGTH = "horse.jump_strength"; + private final Attribute horseJumpStrength; + + public AttributeMapper(mcMMO pluginRef) { + this.pluginRef = pluginRef; + this.horseJumpStrength = initHorseJumpStrength(); + } + + private Attribute initHorseJumpStrength() { + // TODO: Use modern matching? +// if (Registry.ATTRIBUTE.match(GENERIC_JUMP_STRENGTH) != null) { +// return Registry.ATTRIBUTE.match(GENERIC_JUMP_STRENGTH); +// } +// +// if (Registry.ATTRIBUTE.match(HORSE_JUMP_STRENGTH) != null) { +// return Registry.ATTRIBUTE.match(HORSE_JUMP_STRENGTH); +// } + + for (Attribute attr : Registry.ATTRIBUTE) { + if (attr.getKey().getKey().equalsIgnoreCase(HORSE_JUMP_STRENGTH) + || attr.getKey().getKey().equalsIgnoreCase(GENERIC_JUMP_STRENGTH) + || attr.name().equalsIgnoreCase(HORSE_JUMP_STRENGTH) + || attr.name().equalsIgnoreCase(GENERIC_JUMP_STRENGTH)) { + return attr; + } + } + + pluginRef.getLogger().severe("Unable to find the Generic Jump Strength or Horse Jump Strength attribute, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Generic Jump Strength or Horse Jump Strength attribute"); + } + + public Attribute getHorseJumpStrength() { + return horseJumpStrength; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/BlockUtils.java b/src/main/java/com/gmail/nossr50/util/BlockUtils.java index 6edb342a5..da52b9f20 100644 --- a/src/main/java/com/gmail/nossr50/util/BlockUtils.java +++ b/src/main/java/com/gmail/nossr50/util/BlockUtils.java @@ -2,11 +2,13 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.config.experience.ExperienceConfig; import com.gmail.nossr50.datatypes.meta.BonusDropMeta; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.repair.Repair; import com.gmail.nossr50.skills.salvage.Salvage; +import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.random.ProbabilityUtil; import org.bukkit.Material; import org.bukkit.World; @@ -16,9 +18,12 @@ import org.bukkit.block.data.Ageable; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.HashSet; +import static java.util.Objects.requireNonNull; + public final class BlockUtils { public static final String SHORT_GRASS = "SHORT_GRASS"; @@ -60,10 +65,10 @@ public final class BlockUtils { * @param block target block */ public static void setUnnaturalBlock(@NotNull Block block) { - mcMMO.getPlaceStore().setTrue(block); + mcMMO.getUserBlockTracker().setIneligible(block); // Failsafe against lingering metadata - if(block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) + if (block.hasMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS)) block.removeMetadata(MetadataConstants.METADATA_KEY_BONUS_DROPS, mcMMO.p); } @@ -73,11 +78,11 @@ public final class BlockUtils { * @param block target block */ public static void cleanupBlockMetadata(Block block) { - if(block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { + if (block.hasMetadata(MetadataConstants.METADATA_KEY_REPLANT)) { block.removeMetadata(MetadataConstants.METADATA_KEY_REPLANT, mcMMO.p); } - mcMMO.getPlaceStore().setFalse(block); + mcMMO.getUserBlockTracker().setEligible(block); } /** @@ -94,10 +99,28 @@ public final class BlockUtils { * * @param blockState the blockstate * @return true if the player succeeded in the check + * @deprecated Use {@link #checkDoubleDrops(McMMOPlayer, BlockState, SubSkillType)} instead */ - public static boolean checkDoubleDrops(Player player, BlockState blockState, PrimarySkillType skillType, SubSkillType subSkillType) { - if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(skillType, blockState.getType()) && Permissions.isSubSkillEnabled(player, subSkillType)) { - return ProbabilityUtil.isSkillRNGSuccessful(subSkillType, player); + @Deprecated(forRemoval = true, since = "2.2.010") + public static boolean checkDoubleDrops(Player player, BlockState blockState, PrimarySkillType ignored, SubSkillType subSkillType) { + return checkDoubleDrops(UserManager.getPlayer(player), blockState, subSkillType); + } + + /** + * Checks if a player successfully passed the double drop check + * + * @param mmoPlayer the player involved in the check + * @param blockState the blockstate of the block + * @param subSkillType the subskill involved + * @return true if the player succeeded in the check + */ + public static boolean checkDoubleDrops(@Nullable McMMOPlayer mmoPlayer, @NotNull BlockState blockState, + @NotNull SubSkillType subSkillType) { + requireNonNull(blockState, "blockState cannot be null"); + requireNonNull(subSkillType, "subSkillType cannot be null"); + if (mcMMO.p.getGeneralConfig().getDoubleDropsEnabled(subSkillType.getParentSkill(), blockState.getType()) + && Permissions.isSubSkillEnabled(mmoPlayer, subSkillType)) { + return ProbabilityUtil.isSkillRNGSuccessful(subSkillType, mmoPlayer); } return false; @@ -184,7 +207,7 @@ public final class BlockUtils { * otherwise */ public static boolean affectedBySuperBreaker(BlockState blockState) { - if(mcMMO.getMaterialMapStore().isIntendedToolPickaxe(blockState.getType())) + if (mcMMO.getMaterialMapStore().isIntendedToolPickaxe(blockState.getType())) return true; if (ExperienceConfig.getInstance().doesBlockGiveSkillXP(PrimarySkillType.MINING, blockState.getBlockData())) diff --git a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java index e6ea0582c..849728d9b 100644 --- a/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java +++ b/src/main/java/com/gmail/nossr50/util/ChimaeraWing.java @@ -54,7 +54,7 @@ public final class ChimaeraWing { mcMMOPlayer = UserManager.getPlayer(player); //Not loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; if (mcMMOPlayer.getTeleportCommenceLocation() != null) { @@ -113,8 +113,7 @@ public final class ChimaeraWing { if (warmup > 0) { NotificationManager.sendPlayerInformation(player, NotificationType.ITEM_MESSAGE, "Teleport.Commencing", String.valueOf(warmup)); mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(player, new ChimaeraWingWarmup(mcMMOPlayer), 20 * warmup); - } - else { + } else { chimaeraExecuteTeleport(); } } @@ -125,14 +124,12 @@ public final class ChimaeraWing { if (mcMMO.p.getGeneralConfig().getChimaeraUseBedSpawn() && player.getBedSpawnLocation() != null) { // player.teleport(player.getBedSpawnLocation()); mcMMO.p.getFoliaLib().getImpl().teleportAsync(player, player.getBedSpawnLocation()); - } - else { + } else { Location spawnLocation = player.getWorld().getSpawnLocation(); if (spawnLocation.getBlock().getType() == Material.AIR) { // player.teleport(spawnLocation); mcMMO.p.getFoliaLib().getImpl().teleportAsync(player, spawnLocation); - } - else { + } else { // player.teleport(player.getWorld().getHighestBlockAt(spawnLocation).getLocation()); mcMMO.p.getFoliaLib().getImpl().teleportAsync(player, player.getWorld().getHighestBlockAt(spawnLocation).getLocation()); } diff --git a/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java new file mode 100644 index 000000000..b06c1fcdc --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/ContainerMetadataUtils.java @@ -0,0 +1,116 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.datatypes.player.McMMOPlayer; +import com.gmail.nossr50.datatypes.skills.PrimarySkillType; +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.player.UserManager; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.bukkit.block.BlockState; +import org.bukkit.entity.Player; +import org.bukkit.persistence.PersistentDataContainer; +import org.bukkit.persistence.PersistentDataHolder; +import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.UUID; + +import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_LEAST_SIG; +import static com.gmail.nossr50.util.MetadataService.NSK_CONTAINER_UUID_MOST_SIG; +import static java.util.Objects.requireNonNull; + +public class ContainerMetadataUtils { + + public static void changeContainerOwnership(@NotNull BlockState blockState, @NotNull Player player) { + requireNonNull(blockState, "blockState cannot be null"); + requireNonNull(player, "Player cannot be null"); + + final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); + + /* + Debug output + */ + printOwnershipGainDebug(blockState, mmoPlayer); + printOwnershipLossDebug(blockState); + setOwner(blockState, player.getUniqueId()); + } + + public static void printOwnershipGainDebug(@NotNull BlockState blockState, @Nullable McMMOPlayer mmoPlayer) { + if (mmoPlayer != null && mmoPlayer.isDebugMode()) { + mmoPlayer.getPlayer().sendMessage("Container ownership " + + ChatColor.GREEN +"gained " + ChatColor.RESET + + "at location: " + blockState.getLocation().toString()); + } + } + + public static void printOwnershipLossDebug(BlockState blockState) { + OfflinePlayer containerOwner = getContainerOwner(blockState); + + if (containerOwner != null && containerOwner.isOnline()) { + final McMMOPlayer mmoContainerOwner = UserManager.getPlayer(containerOwner.getPlayer()); + + if (mmoContainerOwner != null) { + if (mmoContainerOwner.isDebugMode()) { + mmoContainerOwner.getPlayer().sendMessage("Container ownership " + + ChatColor.RED + "lost " + ChatColor.RESET + + "at location: " + blockState.getLocation().toString()); + } + } + } + } + + public static @Nullable OfflinePlayer getContainerOwner(BlockState container) { + if (container instanceof PersistentDataHolder persistentDataHolder) { + final UUID uuid = getOwner(persistentDataHolder); + + if (uuid != null) { + return Bukkit.getOfflinePlayer(uuid); + } + } + + return null; + } + + + public static boolean isContainerOwned(BlockState blockState) { + return getContainerOwner(blockState) != null; + } + + public static void processContainerOwnership(BlockState blockState, Player player) { + if (!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) + return; + + if (getContainerOwner(blockState) != null) { + if (getContainerOwner(blockState).getUniqueId().equals(player.getUniqueId())) + return; + } + + changeContainerOwnership(blockState, player); + } + + public static @Nullable UUID getOwner(@NotNull PersistentDataHolder persistentDataHolder) { + //Get container from entity + final PersistentDataContainer dataContainer = persistentDataHolder.getPersistentDataContainer(); + + //Too lazy to make a custom data type for this stuff + final Long mostSigBits = dataContainer.get(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG); + final Long leastSigBits = dataContainer.get(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG); + + if (mostSigBits != null && leastSigBits != null) { + return new UUID(mostSigBits, leastSigBits); + } else { + return null; + } + } + + public static void setOwner(@NotNull BlockState blockState, @NotNull UUID uuid) { + PersistentDataContainer dataContainer = ((PersistentDataHolder) blockState).getPersistentDataContainer(); + + dataContainer.set(NSK_CONTAINER_UUID_MOST_SIG, PersistentDataType.LONG, uuid.getMostSignificantBits()); + dataContainer.set(NSK_CONTAINER_UUID_LEAST_SIG, PersistentDataType.LONG, uuid.getLeastSignificantBits()); + + blockState.update(); + } +} diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java new file mode 100644 index 000000000..f4be9209c --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentMapper.java @@ -0,0 +1,149 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.Registry; +import org.bukkit.enchantments.Enchantment; + +public class EnchantmentMapper { + private final mcMMO pluginRef; + private final Enchantment efficiency; + private final Enchantment unbreaking; + private final Enchantment infinity; + private final Enchantment featherFalling; + private final Enchantment luckOfTheSea; + + public EnchantmentMapper(mcMMO pluginRef) { + this.pluginRef = pluginRef; + this.efficiency = initEfficiency(); + this.unbreaking = initUnbreaking(); + this.infinity = initInfinity(); + this.featherFalling = initFeatherFalling(); + this.luckOfTheSea = initLuckOfTheSea(); + } + + private Enchantment initLuckOfTheSea() { + // TODO: Make use of match if present +// if (Registry.ENCHANTMENT.match("luck_of_the_sea") != null) { +// return Registry.ENCHANTMENT.match("luck_of_the_sea"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("LUCK_OF_THE_SEA") + || enchantment.getKey().getKey().equalsIgnoreCase("LUCK") + || enchantment.getName().equalsIgnoreCase("LUCK_OF_THE_SEA") + || enchantment.getName().equalsIgnoreCase("LUCK")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Luck of the Sea enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Luck of the Sea enchantment"); + } + + private Enchantment initFeatherFalling() { +// if (Registry.ENCHANTMENT.match("feather_falling") != null) { +// return Registry.ENCHANTMENT.match("feather_falling"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("FEATHER_FALLING") + || enchantment.getKey().getKey().equalsIgnoreCase("PROTECTION_FALL") + || enchantment.getName().equalsIgnoreCase("FEATHER_FALLING") + || enchantment.getName().equalsIgnoreCase("PROTECTION_FALL")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Feather Falling enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Feather Falling enchantment"); + } + + private Enchantment initInfinity() { +// if (Registry.ENCHANTMENT.match("infinity") != null) { +// return Registry.ENCHANTMENT.match("infinity"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("INFINITY") + || enchantment.getKey().getKey().equalsIgnoreCase("ARROW_INFINITE") + || enchantment.getName().equalsIgnoreCase("INFINITY") + || enchantment.getName().equalsIgnoreCase("ARROW_INFINITE")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Infinity enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Infinity enchantment"); + } + + private Enchantment initEfficiency() { +// if (Registry.ENCHANTMENT.match("efficiency") != null) { +// return Registry.ENCHANTMENT.match("efficiency"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("EFFICIENCY") + || enchantment.getKey().getKey().equalsIgnoreCase("DIG_SPEED") + || enchantment.getName().equalsIgnoreCase("EFFICIENCY") + || enchantment.getName().equalsIgnoreCase("DIG_SPEED")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Efficiency enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Efficiency enchantment"); + } + + private Enchantment initUnbreaking() { +// if (Registry.ENCHANTMENT.match("unbreaking") != null) { +// return Registry.ENCHANTMENT.match("unbreaking"); +// } + + // Look for the enchantment by name + for (Enchantment enchantment : Registry.ENCHANTMENT) { + if (enchantment.getKey().getKey().equalsIgnoreCase("UNBREAKING") + || enchantment.getKey().getKey().equalsIgnoreCase("DURABILITY") + || enchantment.getName().equalsIgnoreCase("UNBREAKING") + || enchantment.getName().equalsIgnoreCase("DURABILITY")) { + return enchantment; + } + } + + pluginRef.getLogger().severe("Unable to find the Unbreaking enchantment, " + + "mcMMO will not function properly."); + throw new IllegalStateException("Unable to find the Unbreaking enchantment"); + } + + /** + * Get the efficiency enchantment + * + * @return The efficiency enchantment + */ + public Enchantment getEfficiency() { + return efficiency; + } + + public Enchantment getUnbreaking() { + return unbreaking; + } + + public Enchantment getInfinity() { + return infinity; + } + + public Enchantment getFeatherFalling() { + return featherFalling; + } + + public Enchantment getLuckOfTheSea() { + return luckOfTheSea; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java index 6aab49b3d..9e0850ed7 100644 --- a/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EnchantmentUtils.java @@ -1,39 +1,34 @@ package com.gmail.nossr50.util; import org.bukkit.enchantments.Enchantment; +import org.jetbrains.annotations.Nullable; import java.util.HashMap; public class EnchantmentUtils { - private static final HashMap enchants = new HashMap<>(); + private static final HashMap legacyEnchantments = new HashMap<>(); static { - enchants.put("SHARPNESS", Enchantment.DAMAGE_ALL); - enchants.put("POWER", Enchantment.ARROW_DAMAGE); - enchants.put("FIRE_PROTECTION", Enchantment.PROTECTION_FIRE); - enchants.put("FEATHER_FALLING", Enchantment.PROTECTION_FALL); - enchants.put("PROTECTION", Enchantment.PROTECTION_ENVIRONMENTAL); - enchants.put("BLAST_PROTECTION", Enchantment.PROTECTION_EXPLOSIONS); - enchants.put("PROJECTILE_PROTECTION", Enchantment.PROTECTION_PROJECTILE); - enchants.put("RESPIRATION", Enchantment.OXYGEN); - enchants.put("INFINITY", Enchantment.ARROW_INFINITE); - enchants.put("AQUA_AFFINITY", Enchantment.WATER_WORKER); - enchants.put("UNBREAKING", Enchantment.DURABILITY); - enchants.put("SMITE", Enchantment.DAMAGE_UNDEAD); - enchants.put("BANE_OF_ARTHROPODS", Enchantment.DAMAGE_ARTHROPODS); - enchants.put("EFFICIENCY", Enchantment.DIG_SPEED); - enchants.put("FIRE_ASPECT", Enchantment.FIRE_ASPECT); - enchants.put("SILK_TOUCH", Enchantment.SILK_TOUCH); - enchants.put("FORTUNE", Enchantment.LOOT_BONUS_BLOCKS); - enchants.put("LOOTING", Enchantment.LOOT_BONUS_MOBS); - enchants.put("PUNCH", Enchantment.ARROW_KNOCKBACK); - enchants.put("FLAME", Enchantment.ARROW_FIRE); - enchants.put("KNOCKBACK", Enchantment.KNOCKBACK); - enchants.put("THORNS", Enchantment.THORNS); - enchants.put("MENDING", Enchantment.MENDING); - enchants.put("DEPTH_STRIDER", Enchantment.DEPTH_STRIDER); - enchants.put("FROST_WALKER", Enchantment.FROST_WALKER); + // backwards compatibility for looking up legacy bukkit enums + addLegacyEnchantmentLookup("SHARPNESS", "DAMAGE_ALL"); + addLegacyEnchantmentLookup("POWER", "ARROW_DAMAGE"); + addLegacyEnchantmentLookup("FIRE_PROTECTION", "PROTECTION_FIRE"); + addLegacyEnchantmentLookup("FEATHER_FALLING", "PROTECTION_FALL"); + addLegacyEnchantmentLookup("PROTECTION", "PROTECTION_ENVIRONMENTAL"); + addLegacyEnchantmentLookup("BLAST_PROTECTION", "PROTECTION_EXPLOSIONS"); + addLegacyEnchantmentLookup("PROJECTILE_PROTECTION", "PROTECTION_PROJECTILE"); + addLegacyEnchantmentLookup("RESPIRATION", "OXYGEN"); + addLegacyEnchantmentLookup("INFINITY", "ARROW_INFINITE"); + addLegacyEnchantmentLookup("AQUA_AFFINITY", "WATER_WORKER"); + addLegacyEnchantmentLookup("UNBREAKING", "DURABILITY"); + addLegacyEnchantmentLookup("SMITE", "DAMAGE_UNDEAD"); + addLegacyEnchantmentLookup("BANE_OF_ARTHROPODS", "DAMAGE_ARTHROPODS"); + addLegacyEnchantmentLookup("EFFICIENCY", "DIG_SPEED"); + addLegacyEnchantmentLookup("FORTUNE", "LOOT_BONUS_BLOCKS"); + addLegacyEnchantmentLookup("LOOTING", "LOOT_BONUS_MOBS"); + addLegacyEnchantmentLookup("PUNCH", "ARROW_KNOCKBACK"); + addLegacyEnchantmentLookup("FLAME", "ARROW_FIRE"); } /** @@ -43,11 +38,19 @@ public class EnchantmentUtils { * * @return Enchantment or null if no enchantment was found */ - public static Enchantment getByName(String enchantmentName) { - if (enchants.containsKey(enchantmentName)) { - return enchants.get(enchantmentName); + @SuppressWarnings("deprecation") + public static @Nullable Enchantment getByName(String enchantmentName) { + if (legacyEnchantments.containsKey(enchantmentName)) { + return legacyEnchantments.get(enchantmentName); } return Enchantment.getByName(enchantmentName); } + + @SuppressWarnings("deprecation") + private static void addLegacyEnchantmentLookup(String enchantmentName, String legacyBukkitName) { + if (Enchantment.getByName(legacyBukkitName) != null) { + legacyEnchantments.put(enchantmentName, Enchantment.getByName(legacyBukkitName)); + } + } } diff --git a/src/main/java/com/gmail/nossr50/util/EventUtils.java b/src/main/java/com/gmail/nossr50/util/EventUtils.java index f53fde6df..de0cb1340 100644 --- a/src/main/java/com/gmail/nossr50/util/EventUtils.java +++ b/src/main/java/com/gmail/nossr50/util/EventUtils.java @@ -10,7 +10,6 @@ import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; -import com.gmail.nossr50.datatypes.skills.subskills.AbstractSubSkill; import com.gmail.nossr50.events.experience.McMMOPlayerLevelChangeEvent; import com.gmail.nossr50.events.experience.McMMOPlayerLevelDownEvent; import com.gmail.nossr50.events.experience.McMMOPlayerLevelUpEvent; @@ -59,6 +58,8 @@ import org.jetbrains.annotations.NotNull; import java.util.HashMap; import java.util.Map; +import static java.util.Objects.requireNonNull; + /** * This class is meant to help make event related code less boilerplate */ @@ -92,8 +93,7 @@ public final class EventUtils { * @param entity target entity * @return the associated McMMOPlayer for this entity */ - public static McMMOPlayer getMcMMOPlayer(@NotNull Entity entity) - { + public static McMMOPlayer getMcMMOPlayer(@NotNull Entity entity) { return UserManager.getPlayer((Player)entity); } @@ -110,8 +110,7 @@ public final class EventUtils { * @param entityDamageEvent * @return */ - public static boolean isRealPlayerDamaged(@NotNull EntityDamageEvent entityDamageEvent) - { + public static boolean isRealPlayerDamaged(@NotNull EntityDamageEvent entityDamageEvent) { //Make sure the damage is above 0 double damage = entityDamageEvent.getFinalDamage(); @@ -122,7 +121,7 @@ public final class EventUtils { Entity entity = entityDamageEvent.getEntity(); //Check to make sure the entity is not an NPC - if(Misc.isNPCEntityExcludingVillagers(entity)) + if (Misc.isNPCEntityExcludingVillagers(entity)) return false; if (!entity.isValid() || !(entity instanceof LivingEntity livingEntity)) { @@ -142,8 +141,7 @@ public final class EventUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) - { + if (mcMMOPlayer == null) { return true; } @@ -163,8 +161,17 @@ public final class EventUtils { * Others */ - public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull Player player, @NotNull PrimarySkillType skill) { - McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(player, skill); + @Deprecated(forRemoval = true, since = "2.2.010") + public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull Player player, + @NotNull PrimarySkillType skill) { + return callPlayerAbilityActivateEvent(requireNonNull(UserManager.getPlayer(player)), skill); + } + + public static @NotNull McMMOPlayerAbilityActivateEvent callPlayerAbilityActivateEvent(@NotNull McMMOPlayer mmoPlayer, + @NotNull PrimarySkillType skill) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); + requireNonNull(skill, "skill cannot be null"); + McMMOPlayerAbilityActivateEvent event = new McMMOPlayerAbilityActivateEvent(mmoPlayer, skill); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; @@ -183,8 +190,21 @@ public final class EventUtils { * @param subSkillType target subskill * @return the event after it has been fired */ + @Deprecated(forRemoval = true, since = "2.2.010") public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull Player player, @NotNull SubSkillType subSkillType) { - SubSkillEvent event = new SubSkillEvent(player, subSkillType); + return callSubSkillEvent(requireNonNull(UserManager.getPlayer(player)), subSkillType); + } + + /** + * Calls a new SubSkillEvent for this SubSkill and then returns it + * @param mmoPlayer target mmoPlayer + * @param subSkillType target subskill + * @return the event after it has been fired + */ + public static @NotNull SubSkillEvent callSubSkillEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { + requireNonNull(mmoPlayer, "mmoPlayer cannot be null"); + requireNonNull(subSkillType, "subSkillType cannot be null"); + final SubSkillEvent event = new SubSkillEvent(mmoPlayer, subSkillType); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; @@ -204,26 +224,6 @@ public final class EventUtils { return event; } - /** - * Calls a new SubSkillEvent for this SubSkill and then returns it - * @param player target player - * @param abstractSubSkill target subskill - * @return the event after it has been fired - */ - public static SubSkillEvent callSubSkillEvent(Player player, AbstractSubSkill abstractSubSkill) { - SubSkillEvent event = new SubSkillEvent(player, abstractSubSkill); - mcMMO.p.getServer().getPluginManager().callEvent(event); - - return event; - } - -// public static Event callFakeArmSwingEvent(@NotNull Player player) { -// PlayerAnimationEvent event = new FakePlayerAnimationEvent(player, PlayerAnimationType.ARM_SWING); -// mcMMO.p.getServer().getPluginManager().callEvent(event); -// -// return event; -// } - public static boolean tryLevelChangeEvent(Player player, PrimarySkillType skill, int levelsChanged, float xpRemoved, boolean isLevelUp, XPGainReason xpGainReason) { McMMOPlayerLevelChangeEvent event = isLevelUp ? new McMMOPlayerLevelUpEvent(player, skill, levelsChanged, xpGainReason) : new McMMOPlayerLevelDownEvent(player, skill, levelsChanged, xpGainReason); mcMMO.p.getServer().getPluginManager().callEvent(event); @@ -347,7 +347,7 @@ public final class EventUtils { public static void handlePartyTeleportEvent(Player teleportingPlayer, Player targetPlayer) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(teleportingPlayer); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; McMMOPartyTeleportEvent event = new McMMOPartyTeleportEvent(teleportingPlayer, targetPlayer, mcMMOPlayer.getParty().getName()); @@ -395,7 +395,7 @@ public final class EventUtils { public static boolean handleXpGainEvent(Player player, PrimarySkillType skill, float xpGained, XPGainReason xpGainReason) { McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if(mmoPlayer == null) + if (mmoPlayer == null) return true; McMMOPlayerXpGainEvent event = new McMMOPlayerXpGainEvent(player, skill, xpGained, xpGainReason); @@ -412,7 +412,7 @@ public final class EventUtils { } public static boolean handleStatsLossEvent(Player player, HashMap levelChanged, HashMap experienceChanged) { - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return true; McMMOPlayerStatLossEvent event = new McMMOPlayerStatLossEvent(player, levelChanged, experienceChanged); @@ -429,7 +429,7 @@ public final class EventUtils { String skillName = primarySkillType.toString(); int playerSkillLevel = playerProfile.getSkillLevel(primarySkillType); int threshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold(); - if(playerSkillLevel > threshold) { + if (playerSkillLevel > threshold) { playerProfile.modifySkill(primarySkillType, Math.max(threshold, playerSkillLevel - levelChanged.get(skillName))); playerProfile.removeXp(primarySkillType, experienceChanged.get(skillName)); @@ -465,11 +465,11 @@ public final class EventUtils { McMMOPlayer killerPlayer = UserManager.getPlayer(killer); //Not loaded - if(killerPlayer == null) + if (killerPlayer == null) return true; //Not loaded - if(UserManager.getPlayer(victim) == null) + if (UserManager.getPlayer(victim) == null) return true; PlayerProfile victimProfile = UserManager.getPlayer(victim).getProfile(); @@ -497,15 +497,25 @@ public final class EventUtils { return !isCancelled; } + @Deprecated(forRemoval = true, since = "2.2.010") public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(Player player, SuperAbilityType ability) { - McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(player, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability)); + return callAbilityDeactivateEvent(requireNonNull(UserManager.getPlayer(player)), ability); + } + + public static McMMOPlayerAbilityDeactivateEvent callAbilityDeactivateEvent(@NotNull McMMOPlayer mmoPlayer, @NotNull SuperAbilityType ability) { + final McMMOPlayerAbilityDeactivateEvent event = new McMMOPlayerAbilityDeactivateEvent(mmoPlayer, mcMMO.p.getSkillTools().getPrimarySkillBySuperAbility(ability)); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; } + @Deprecated(forRemoval = true, since = "2.2.010") public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(Player player, ItemStack treasureDrop, int treasureXp, Map enchants) { - McMMOPlayerFishingTreasureEvent event = enchants.isEmpty() ? new McMMOPlayerFishingTreasureEvent(player, treasureDrop, treasureXp) : new McMMOPlayerMagicHunterEvent(player, treasureDrop, treasureXp, enchants); + return callFishingTreasureEvent(requireNonNull(UserManager.getPlayer(player)), treasureDrop, treasureXp, enchants); + } + + public static McMMOPlayerFishingTreasureEvent callFishingTreasureEvent(McMMOPlayer mmoPlayer, ItemStack treasureDrop, int treasureXp, Map enchants) { + final McMMOPlayerFishingTreasureEvent event = enchants.isEmpty() ? new McMMOPlayerFishingTreasureEvent(mmoPlayer, treasureDrop, treasureXp) : new McMMOPlayerMagicHunterEvent(mmoPlayer, treasureDrop, treasureXp, enchants); mcMMO.p.getServer().getPluginManager().callEvent(event); return event; diff --git a/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java b/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java index a9e6b4bea..9f5b9dd52 100644 --- a/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java +++ b/src/main/java/com/gmail/nossr50/util/FixSpellingNetheriteUtil.java @@ -11,7 +11,7 @@ public class FixSpellingNetheriteUtil { LogUtils.debug(mcMMO.p.getLogger(), "Checking " + fileName + " config material names..."); File configFile = new File(pluginRef.getDataFolder(), fileName); - if(configFile.exists()) { + if (configFile.exists()) { BufferedReader bufferedReader = null; FileWriter fileWriter = null; try { @@ -35,14 +35,14 @@ public class FixSpellingNetheriteUtil { } catch (IOException e) { e.printStackTrace(); } finally { - if(bufferedReader != null) { + if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } - if(fileWriter != null) { + if (fileWriter != null) { try { fileWriter.close(); } catch (IOException e) { diff --git a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java index 491074a5e..01b085952 100644 --- a/src/main/java/com/gmail/nossr50/util/HardcoreManager.java +++ b/src/main/java/com/gmail/nossr50/util/HardcoreManager.java @@ -18,15 +18,15 @@ public final class HardcoreManager { public static void invokeStatPenalty(Player player) { - if(WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasHardcoreFlag(player)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasHardcoreFlag(player)) return; } double statLossPercentage = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyPercentage(); int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreDeathStatPenaltyLevelThreshold(); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return; PlayerProfile playerProfile = UserManager.getPlayer(player).getProfile(); @@ -69,15 +69,15 @@ public final class HardcoreManager { public static void invokeVampirism(Player killer, Player victim) { - if(WorldGuardUtils.isWorldGuardLoaded()) { - if(!WorldGuardManager.getInstance().hasHardcoreFlag(killer) || !WorldGuardManager.getInstance().hasHardcoreFlag(victim)) + if (WorldGuardUtils.isWorldGuardLoaded()) { + if (!WorldGuardManager.getInstance().hasHardcoreFlag(killer) || !WorldGuardManager.getInstance().hasHardcoreFlag(victim)) return; } double vampirismStatLeechPercentage = mcMMO.p.getGeneralConfig().getHardcoreVampirismStatLeechPercentage(); int levelThreshold = mcMMO.p.getGeneralConfig().getHardcoreVampirismLevelThreshold(); - if(UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null) + if (UserManager.getPlayer(killer) == null || UserManager.getPlayer(victim) == null) return; PlayerProfile killerProfile = UserManager.getPlayer(killer).getProfile(); @@ -121,8 +121,7 @@ public final class HardcoreManager { if (totalLevelsStolen > 0) { NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Success", String.valueOf(totalLevelsStolen), victim.getName()); NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Success", killer.getName(), String.valueOf(totalLevelsStolen)); - } - else { + } else { NotificationManager.sendPlayerInformation(killer, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Killer.Failure", victim.getName()); NotificationManager.sendPlayerInformation(victim, NotificationType.HARDCORE_MODE, "Hardcore.Vampirism.Victim.Failure", killer.getName()); } diff --git a/src/main/java/com/gmail/nossr50/util/HolidayManager.java b/src/main/java/com/gmail/nossr50/util/HolidayManager.java index 6ea18317b..37adbbc1b 100644 --- a/src/main/java/com/gmail/nossr50/util/HolidayManager.java +++ b/src/main/java/com/gmail/nossr50/util/HolidayManager.java @@ -313,7 +313,7 @@ // } // // public boolean isAprilFirst() { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return false; // // GregorianCalendar aprilFirst = new GregorianCalendar(currentYear, Calendar.APRIL, 1); @@ -323,7 +323,7 @@ // } // // public boolean nearingAprilFirst() { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return false; // // GregorianCalendar start = new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR), Calendar.MARCH, 28); @@ -366,7 +366,7 @@ // } // // public void levelUpApril(Player player, FakeSkillType fakeSkillType) { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return; // // final McMMOPlayer mmoPlayer = UserManager.getPlayer(player); @@ -379,7 +379,7 @@ // } // // public void registerAprilCommand() { -// if(!Config.getInstance().isAprilFoolsAllowed()) +// if (!Config.getInstance().isAprilFoolsAllowed()) // return; // // PluginCommand command = mcMMO.p.getCommand("crafting"); diff --git a/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java similarity index 70% rename from src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java rename to src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java index f1d1e9471..ff565f71d 100644 --- a/src/main/java/com/gmail/nossr50/metadata/ItemMetadataService.java +++ b/src/main/java/com/gmail/nossr50/util/ItemMetadataUtils.java @@ -1,7 +1,6 @@ -package com.gmail.nossr50.metadata; +package com.gmail.nossr50.util; import com.gmail.nossr50.mcMMO; -import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; @@ -10,18 +9,17 @@ import org.jetbrains.annotations.NotNull; import java.util.List; -import static com.gmail.nossr50.metadata.MetadataService.NSK_SUPER_ABILITY_BOOSTED_ITEM; +import static com.gmail.nossr50.util.MetadataService.NSK_SUPER_ABILITY_BOOSTED_ITEM; -public class ItemMetadataService { +public final class ItemMetadataUtils { - public final @NotNull String LEGACY_ABILITY_TOOL_LORE = "mcMMO Ability Tool"; - public final @NotNull mcMMO pluginRef; + public static final @NotNull String LEGACY_ABILITY_TOOL_LORE = "mcMMO Ability Tool"; - public ItemMetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; + private ItemMetadataUtils() { + // private ctor } - public void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed) { + public static void setSuperAbilityBoostedItem(@NotNull ItemStack itemStack, int originalDigSpeed) { if (itemStack.getItemMeta() == null) { mcMMO.p.getLogger().severe("Can not assign persistent data to an item with null item metadata"); return; @@ -35,7 +33,7 @@ public class ItemMetadataService { itemStack.setItemMeta(itemMeta); } - public boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) { + public static boolean isSuperAbilityBoosted(@NotNull ItemStack itemStack) { if (itemStack.getItemMeta() == null) return false; @@ -49,7 +47,7 @@ public class ItemMetadataService { return boostValue != null; } - public int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack) { + public static int getSuperAbilityToolOriginalDigSpeed(@NotNull ItemStack itemStack) { //Get container from entity ItemMeta itemMeta = itemStack.getItemMeta(); @@ -68,18 +66,18 @@ public class ItemMetadataService { } } - public void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack) { + public static void removeBonusDigSpeedOnSuperAbilityTool(@NotNull ItemStack itemStack) { int originalSpeed = getSuperAbilityToolOriginalDigSpeed(itemStack); ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta != null) { + if (itemMeta != null) { //TODO: can be optimized - if (itemMeta.hasEnchant(Enchantment.DIG_SPEED)) { - itemMeta.removeEnchant(Enchantment.DIG_SPEED); + if (itemMeta.hasEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency())) { + itemMeta.removeEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency()); } if (originalSpeed > 0) { - itemMeta.addEnchant(Enchantment.DIG_SPEED, originalSpeed, true); + itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), originalSpeed, true); } PersistentDataContainer dataContainer = itemMeta.getPersistentDataContainer(); @@ -90,7 +88,7 @@ public class ItemMetadataService { } } - public boolean isLegacyAbilityTool(@NotNull ItemStack itemStack) { + public static boolean isLegacyAbilityTool(@NotNull ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta == null) @@ -103,8 +101,4 @@ public class ItemMetadataService { return lore.contains(LEGACY_ABILITY_TOOL_LORE); } - - public @NotNull String getLegacyAbilityToolLore() { - return LEGACY_ABILITY_TOOL_LORE; - } } diff --git a/src/main/java/com/gmail/nossr50/util/ItemUtils.java b/src/main/java/com/gmail/nossr50/util/ItemUtils.java index 6055582e3..e80bf3053 100644 --- a/src/main/java/com/gmail/nossr50/util/ItemUtils.java +++ b/src/main/java/com/gmail/nossr50/util/ItemUtils.java @@ -20,9 +20,13 @@ import org.bukkit.inventory.meta.ItemMeta; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.Collections; import java.util.List; +import static java.util.Objects.requireNonNull; + public final class ItemUtils { /** * This is a static utility class, therefore we don't want any instances of @@ -30,6 +34,43 @@ public final class ItemUtils { */ private ItemUtils() {} + private static final Method setItemName; + + static { + setItemName = getSetItemName(); + } + + private static Method getSetItemName() { + try { + return ItemMeta.class.getMethod("setItemName", String.class); + } catch (NoSuchMethodException e) { + return null; + } + } + + /** + * Sets the item name using the new API if available + * or falls back to the old API. + * @param itemMeta The item meta to set the name on + * @param name The name to set + */ + public static void setItemName(ItemMeta itemMeta, String name) { + if (setItemName != null) { + setItemNameModern(itemMeta, name); + } else { + itemMeta.setDisplayName(ChatColor.RESET + name); + } + } + + private static void setItemNameModern(ItemMeta itemMeta, String name) { + try { + setItemName.invoke(itemMeta, name); + } catch (IllegalAccessException | InvocationTargetException e) { + mcMMO.p.getLogger().severe("Failed to set item name: " + e.getMessage()); + throw new RuntimeException(e); + } + } + /** * Checks if the item is a bow. * @@ -41,6 +82,37 @@ public final class ItemUtils { return mcMMO.getMaterialMapStore().isBow(item.getType().getKey().getKey()); } + /** + * Exhaustive lookup for a Material by name. + *

+ * This method will first try a normal lookup, then a legacy lookup, then a lookup by ENUM name, + * and finally a lookup by ENUM name with legacy name. + * @param materialName The name of the material to lookup + * @return The Material if found, or null if not found + */ + public static @Nullable Material exhaustiveMaterialLookup(@NotNull String materialName) { + requireNonNull(materialName, "materialName cannot be null"); + + // First try a normal lookup + Material material = Material.matchMaterial(materialName); + + // If that fails, try a legacy lookup + if (material == null) { + material = Material.matchMaterial(materialName, true); + } + + // try to match to Material ENUM + if (material == null) { + material = Material.getMaterial(materialName.toUpperCase()); + } + + // try to match to Material ENUM with legacy name + if (material == null) { + material = Material.getMaterial(materialName.toUpperCase(), true); + } + return material; + } + /** * Checks if a player has an item in their inventory or offhand. * @@ -100,6 +172,10 @@ public final class ItemUtils { return mcMMO.getMaterialMapStore().isTrident(item.getType().getKey().getKey()); } + public static boolean isMace(@NotNull ItemStack item) { + return mcMMO.getMaterialMapStore().isMace(item.getType().getKey().getKey()); + } + public static boolean hasItemInEitherHand(@NotNull Player player, Material material) { return player.getInventory().getItemInMainHand().getType() == material || player.getInventory().getItemInOffHand().getType() == material; } @@ -107,7 +183,7 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, @NotNull String enchantmentByName) { Enchantment enchantment = getEnchantment(enchantmentByName); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentOnArmor(player, enchantment); @@ -115,8 +191,8 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentOnArmor(@NotNull Player player, @NotNull Enchantment enchantment) { for(ItemStack itemStack : player.getInventory().getArmorContents()) { - if(itemStack != null) { - if(hasEnchantment(itemStack, enchantment)) + if (itemStack != null) { + if (hasEnchantment(itemStack, enchantment)) return true; } } @@ -127,17 +203,17 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, @NotNull String enchantmentName) { Enchantment enchantment = getEnchantment(enchantmentName); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentOnArmorOrHands(player, enchantment); } public static boolean doesPlayerHaveEnchantmentOnArmorOrHands(@NotNull Player player, @NotNull Enchantment enchantment) { - if(doesPlayerHaveEnchantmentOnArmor(player, enchantment)) + if (doesPlayerHaveEnchantmentOnArmor(player, enchantment)) return true; - if(doesPlayerHaveEnchantmentInHands(player, enchantment)) + if (doesPlayerHaveEnchantmentInHands(player, enchantment)) return true; return false; @@ -146,7 +222,7 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull NamespacedKey enchantmentNameKey) { Enchantment enchantment = Enchantment.getByKey(enchantmentNameKey); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentInHands(player, enchantment); @@ -155,7 +231,7 @@ public final class ItemUtils { public static boolean doesPlayerHaveEnchantmentInHands(@NotNull Player player, @NotNull String enchantmentName) { Enchantment enchantment = getEnchantment(enchantmentName); - if(enchantment == null) + if (enchantment == null) return false; return doesPlayerHaveEnchantmentInHands(player, enchantment); @@ -167,7 +243,7 @@ public final class ItemUtils { } public static boolean hasEnchantment(@NotNull ItemStack itemStack, @NotNull Enchantment enchantment) { - if(itemStack.getItemMeta() != null) { + if (itemStack.getItemMeta() != null) { return itemStack.getItemMeta().hasEnchant(enchantment); } @@ -176,7 +252,7 @@ public final class ItemUtils { public static @Nullable Enchantment getEnchantment(@NotNull String enchantmentName) { for(Enchantment enchantment : Enchantment.values()) { - if(enchantment.getKey().getKey().equalsIgnoreCase(enchantmentName)) { + if (enchantment.getKey().getKey().equalsIgnoreCase(enchantmentName)) { return enchantment; } } @@ -619,7 +695,7 @@ public final class ItemUtils { ItemMeta itemMeta = item.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return false; return itemMeta.getLore() != null @@ -633,7 +709,7 @@ public final class ItemUtils { ItemMeta itemMeta = item.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return false; return itemMeta.hasDisplayName() && itemMeta.getDisplayName().equals(ChatColor.GOLD + LocaleLoader.getString("Item.ChimaeraWing.Name")); @@ -643,7 +719,7 @@ public final class ItemUtils { // ItemMeta itemMeta = itemStack.getItemMeta(); // List itemLore = new ArrayList<>(); // -// if(itemMeta == null) +// if (itemMeta == null) // return; // // if (itemMeta.hasLore()) { @@ -659,13 +735,13 @@ public final class ItemUtils { public static void removeAbilityLore(@NotNull ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return; if (itemMeta.hasLore()) { List itemLore = itemMeta.getLore(); - if(itemLore == null) + if (itemLore == null) return; if (itemLore.remove("mcMMO Ability Tool")) { @@ -678,10 +754,11 @@ public final class ItemUtils { public static void addDigSpeedToItem(@NotNull ItemStack itemStack, int existingEnchantLevel) { ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta == null) + if (itemMeta == null) return; - itemMeta.addEnchant(Enchantment.DIG_SPEED, existingEnchantLevel + mcMMO.p.getAdvancedConfig().getEnchantBuff(), true); + itemMeta.addEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency(), + existingEnchantLevel + mcMMO.p.getAdvancedConfig().getEnchantBuff(), true); itemStack.setItemMeta(itemMeta); } @@ -694,7 +771,7 @@ public final class ItemUtils { EnchantmentWrapper enchantmentWrapper = getRandomEnchantment(fishingTreasureBook.getLegalEnchantments()); ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta == null) { + if (itemMeta == null) { return itemStack; } diff --git a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java index b0f623602..01c6bf8fe 100644 --- a/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java +++ b/src/main/java/com/gmail/nossr50/util/MaterialMapStore.java @@ -50,6 +50,7 @@ public class MaterialMapStore { private final @NotNull HashSet crossbows; private final @NotNull HashSet tools; private final @NotNull HashSet enchantables; + private final @NotNull HashSet maces; private final @NotNull HashSet ores; private final @NotNull HashSet intendedToolPickAxe; @@ -58,8 +59,7 @@ public class MaterialMapStore { private final @NotNull HashMap tierValue; - public MaterialMapStore() - { + public MaterialMapStore() { abilityBlackList = new HashSet<>(); toolBlackList = new HashSet<>(); mossyWhiteList = new HashSet<>(); @@ -97,6 +97,7 @@ public class MaterialMapStore { shovels = new HashSet<>(); hoes = new HashSet<>(); tridents = new HashSet<>(); + maces = new HashSet<>(); enchantables = new HashSet<>(); @@ -131,8 +132,7 @@ public class MaterialMapStore { fillTierMap(); } - public boolean isMultiBlockPlant(@NotNull Material material) - { + public boolean isMultiBlockPlant(@NotNull Material material) { return multiBlockPlant.contains(material.getKey().getKey()); } @@ -140,38 +140,31 @@ public class MaterialMapStore { return multiBlockHangingPlant.contains(material.getKey().getKey()); } - public boolean isAbilityActivationBlackListed(@NotNull Material material) - { + public boolean isAbilityActivationBlackListed(@NotNull Material material) { return abilityBlackList.contains(material.getKey().getKey()); } - public boolean isToolActivationBlackListed(@NotNull Material material) - { + public boolean isToolActivationBlackListed(@NotNull Material material) { return toolBlackList.contains(material.getKey().getKey()); } - public boolean isMossyWhiteListed(@NotNull Material material) - { + public boolean isMossyWhiteListed(@NotNull Material material) { return mossyWhiteList.contains(material.getKey().getKey()); } - public boolean isTreeFellerDestructible(@NotNull Material material) - { + public boolean isTreeFellerDestructible(@NotNull Material material) { return treeFellerDestructibleWhiteList.contains(material.getKey().getKey()); } - public boolean isHerbalismAbilityWhiteListed(@NotNull Material material) - { + public boolean isHerbalismAbilityWhiteListed(@NotNull Material material) { return herbalismAbilityBlackList.contains(material.getKey().getKey()); } - public boolean isBlockCrackerWhiteListed(@NotNull Material material) - { + public boolean isBlockCrackerWhiteListed(@NotNull Material material) { return blockCrackerWhiteList.contains(material.getKey().getKey()); } - public boolean isShroomyWhiteListed(@NotNull Material material) - { + public boolean isShroomyWhiteListed(@NotNull Material material) { return canMakeShroomyWhiteList.contains(material.getKey().getKey()); } @@ -453,6 +446,7 @@ public class MaterialMapStore { enchantables.addAll(tridents); enchantables.addAll(bows); enchantables.addAll(crossbows); + enchantables.addAll(maces); enchantables.add("shears"); enchantables.add("fishing_rod"); @@ -476,6 +470,7 @@ public class MaterialMapStore { fillHoes(); fillShovels(); fillTridents(); + fillMaces(); fillStringTools(); fillBows(); fillCrossbows(); @@ -491,6 +486,7 @@ public class MaterialMapStore { tools.addAll(stringTools); tools.addAll(bows); tools.addAll(crossbows); + tools.addAll(maces); } private void fillBows() { @@ -507,6 +503,10 @@ public class MaterialMapStore { stringTools.add("carrot_on_a_stick"); } + private void fillMaces() { + maces.add("mace"); + } + private void fillTridents() { tridents.add("trident"); } @@ -824,6 +824,14 @@ public class MaterialMapStore { return tridents.contains(id); } + public boolean isMace(@NotNull Material material) { + return isMace(material.getKey().getKey()); + } + + public boolean isMace(@NotNull String id) { + return maces.contains(id); + } + public boolean isLeatherArmor(@NotNull Material material) { return isLeatherArmor(material.getKey().getKey()); } @@ -976,8 +984,7 @@ public class MaterialMapStore { return foodItemWhiteList.contains(material.getKey().getKey()); } - private void fillMultiBlockPlantSet() - { + private void fillMultiBlockPlantSet() { //Multi-Block Plants multiBlockPlant.add("cactus"); multiBlockPlant.add("chorus_plant"); @@ -997,30 +1004,26 @@ public class MaterialMapStore { multiBlockHangingPlant.add("cave_vines_plant"); } - private void fillShroomyWhiteList() - { + private void fillShroomyWhiteList() { canMakeShroomyWhiteList.add("dirt"); canMakeShroomyWhiteList.add("grass_block"); canMakeShroomyWhiteList.add("dirt_path"); } - private void fillBlockCrackerWhiteList() - { + private void fillBlockCrackerWhiteList() { blockCrackerWhiteList.add("stone_bricks"); blockCrackerWhiteList.add("infested_stone_bricks"); } - private void fillHerbalismAbilityBlackList() - { + private void fillHerbalismAbilityBlackList() { herbalismAbilityBlackList.add("dirt"); herbalismAbilityBlackList.add("grass_block"); herbalismAbilityBlackList.add("dirt_path"); herbalismAbilityBlackList.add("farmland"); } - private void fillTreeFellerDestructibleWhiteList() - { + private void fillTreeFellerDestructibleWhiteList() { treeFellerDestructibleWhiteList.add("oak_leaves"); treeFellerDestructibleWhiteList.add("cherry_leaves"); treeFellerDestructibleWhiteList.add("acacia_leaves"); @@ -1038,8 +1041,7 @@ public class MaterialMapStore { treeFellerDestructibleWhiteList.add("red_mushroom_block"); } - private void fillMossyWhiteList() - { + private void fillMossyWhiteList() { mossyWhiteList.add("cobblestone"); mossyWhiteList.add("dirt"); mossyWhiteList.add("grass_path"); @@ -1047,8 +1049,7 @@ public class MaterialMapStore { mossyWhiteList.add("cobblestone_wall"); } - private void fillAbilityBlackList() - { + private void fillAbilityBlackList() { abilityBlackList.add("warped_fence_gate"); abilityBlackList.add("crimson_fence_gate"); abilityBlackList.add("warped_pressure_plate"); @@ -1175,8 +1176,7 @@ public class MaterialMapStore { abilityBlackList.add("respawn_anchor"); } - private void fillToolBlackList() - { + private void fillToolBlackList() { toolBlackList.add("chiseled_bookshelf"); toolBlackList.add("black_bed"); toolBlackList.add("blue_bed"); @@ -1354,8 +1354,7 @@ public class MaterialMapStore { return tierValue.getOrDefault(id, 1); //1 for unknown items } - private void addToHashSet(@NotNull String string, @NotNull HashSet stringHashSet) - { + private void addToHashSet(@NotNull String string, @NotNull HashSet stringHashSet) { stringHashSet.add(string.toLowerCase(Locale.ENGLISH)); } } diff --git a/src/main/java/com/gmail/nossr50/util/MetadataConstants.java b/src/main/java/com/gmail/nossr50/util/MetadataConstants.java index 39f9479ce..d3145e42c 100644 --- a/src/main/java/com/gmail/nossr50/util/MetadataConstants.java +++ b/src/main/java/com/gmail/nossr50/util/MetadataConstants.java @@ -34,8 +34,9 @@ public class MetadataConstants { public static final @NotNull String METADATA_KEY_DISARMED_ITEM = "mcMMO: Disarmed Item"; public static final @NotNull String METADATA_KEY_PLAYER_DATA = "mcMMO: Player Data"; public static final @NotNull String METADATA_KEY_DATABASE_COMMAND = "mcMMO: Processing Database Command"; - public static final @NotNull String METADATA_KEY_FURNACE_UUID_MOST_SIG = "furnace_uuid_most_sig"; - public static final @NotNull String METADATA_KEY_FURNACE_UUID_LEAST_SIG = "furnace_uuid_least_sig"; + // the value of these two keys have "furnace" to keep supporting legacy data + public static final @NotNull String METADATA_KEY_CONTAINER_UUID_MOST_SIG = "furnace_uuid_most_sig"; + public static final @NotNull String METADATA_KEY_CONTAINER_UUID_LEAST_SIG = "furnace_uuid_least_sig"; public static final @NotNull String METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM = "super_ability_boosted"; public static final @NotNull String METADATA_KEY_MOB_SPAWNER_MOB = "mcmmo_mob_spawner_mob"; public static final @NotNull String METADATA_KEY_EGG_MOB = "mcmmo_egg_mob"; diff --git a/src/main/java/com/gmail/nossr50/util/MetadataService.java b/src/main/java/com/gmail/nossr50/util/MetadataService.java new file mode 100644 index 000000000..fac2b83a3 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/MetadataService.java @@ -0,0 +1,48 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.NamespacedKey; +import org.jetbrains.annotations.NotNull; + +public final class MetadataService { + static final @NotNull NamespacedKey NSK_SUPER_ABILITY_BOOSTED_ITEM; + static final @NotNull NamespacedKey NSK_MOB_SPAWNER_MOB; + static final @NotNull NamespacedKey NSK_EGG_MOB; + static final @NotNull NamespacedKey NSK_NETHER_GATE_MOB; + static final @NotNull NamespacedKey NSK_COTW_SUMMONED_MOB; + static final @NotNull NamespacedKey NSK_PLAYER_BRED_MOB; + static final @NotNull NamespacedKey NSK_PLAYER_TAMED_MOB; + static final @NotNull NamespacedKey NSK_VILLAGER_TRADE_ORIGIN_ITEM; + static final @NotNull NamespacedKey NSK_EXPLOITED_ENDERMEN; + static final @NotNull NamespacedKey NSK_CONTAINER_UUID_MOST_SIG; + static final @NotNull NamespacedKey NSK_CONTAINER_UUID_LEAST_SIG; + + private MetadataService() { + // private ctor + } + + static { + NSK_SUPER_ABILITY_BOOSTED_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_SUPER_ABILITY_BOOSTED_ITEM); + NSK_MOB_SPAWNER_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_MOB_SPAWNER_MOB); + NSK_EGG_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_EGG_MOB); + NSK_NETHER_GATE_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_NETHER_PORTAL_MOB); + NSK_COTW_SUMMONED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_COTW_SUMMONED_MOB); + NSK_PLAYER_BRED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_BRED_MOB); + NSK_PLAYER_TAMED_MOB = getNamespacedKey(MetadataConstants.METADATA_KEY_PLAYER_TAMED_MOB); + NSK_VILLAGER_TRADE_ORIGIN_ITEM = getNamespacedKey(MetadataConstants.METADATA_KEY_VILLAGER_TRADE_ORIGIN_ITEM); + NSK_EXPLOITED_ENDERMEN = getNamespacedKey(MetadataConstants.METADATA_KEY_EXPLOITED_ENDERMEN); + NSK_CONTAINER_UUID_MOST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_CONTAINER_UUID_MOST_SIG); + NSK_CONTAINER_UUID_LEAST_SIG = getNamespacedKey(MetadataConstants.METADATA_KEY_CONTAINER_UUID_LEAST_SIG); + } + + /** + * Helper method to simplify generating namespaced keys + * + * @param key the {@link String} value of the key + * + * @return the generated {@link NamespacedKey} + */ + public static @NotNull NamespacedKey getNamespacedKey(@NotNull String key) { + return new NamespacedKey(mcMMO.p, key); + } +} diff --git a/src/main/java/com/gmail/nossr50/util/Misc.java b/src/main/java/com/gmail/nossr50/util/Misc.java index 2467a5540..a289315cb 100644 --- a/src/main/java/com/gmail/nossr50/util/Misc.java +++ b/src/main/java/com/gmail/nossr50/util/Misc.java @@ -223,7 +223,7 @@ public final class Misc { Location spawnLocation = fromLocation.clone(); Location targetLocation = toLocation.clone(); - if(spawnLocation.getWorld() == null) + if (spawnLocation.getWorld() == null) return null; // We can't get the item until we spawn it and we want to make it cancellable, so we have a custom event. @@ -318,7 +318,7 @@ public final class Misc { // } public static void spawnExperienceOrb(@NotNull Location location, int experienceValue) { - if(location.getWorld() == null) + if (location.getWorld() == null) return; ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB); @@ -336,7 +336,7 @@ public final class Misc { @Override public void run() { - if(location == null || location.getWorld() == null) + if (location == null || location.getWorld() == null) return; ExperienceOrb experienceOrb = (ExperienceOrb) location.getWorld().spawnEntity(location, EntityType.EXPERIENCE_ORB); @@ -352,7 +352,7 @@ public final class Misc { // // double win = 0, loss = 0; // for(int x = 0; x < iterations; x++) { -// if(RandomChanceUtil.checkRandomChanceExecutionSuccess(normalPlayer.getPlayer(), SubSkillType.MINING_MOTHER_LODE, true)) { +// if (RandomChanceUtil.checkRandomChanceExecutionSuccess(normalPlayer.getPlayer(), SubSkillType.MINING_MOTHER_LODE, true)) { // win++; // } else { // loss++; diff --git a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java index 5da29a656..02f80a306 100644 --- a/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java +++ b/src/main/java/com/gmail/nossr50/util/MobHealthbarUtils.java @@ -54,7 +54,7 @@ public final class MobHealthbarUtils { /* * Store the name in metadata */ - if(target.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY).size() <= 0) + if (target.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY).size() <= 0) target.setMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY, new OldName(originalName, plugin)); if (oldName == null) { @@ -75,8 +75,7 @@ public final class MobHealthbarUtils { if (updateName) { target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, new FixedMetadataValue(mcMMO.p, oldName)); target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, new FixedMetadataValue(mcMMO.p, oldNameVisible)); - } - else if (!target.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { + } else if (!target.hasMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME)) { target.setMetadata(MetadataConstants.METADATA_KEY_CUSTOM_NAME, new FixedMetadataValue(mcMMO.p, "")); target.setMetadata(MetadataConstants.METADATA_KEY_NAME_VISIBILITY, new FixedMetadataValue(mcMMO.p, false)); } @@ -106,20 +105,15 @@ public final class MobHealthbarUtils { if (healthPercentage >= 85) { color = ChatColor.DARK_GREEN; - } - else if (healthPercentage >= 70) { + } else if (healthPercentage >= 70) { color = ChatColor.GREEN; - } - else if (healthPercentage >= 55) { + } else if (healthPercentage >= 55) { color = ChatColor.GOLD; - } - else if (healthPercentage >= 40) { + } else if (healthPercentage >= 40) { color = ChatColor.YELLOW; - } - else if (healthPercentage >= 25) { + } else if (healthPercentage >= 25) { color = ChatColor.RED; - } - else if (healthPercentage >= 0) { + } else if (healthPercentage >= 0) { color = ChatColor.DARK_RED; } diff --git a/src/main/java/com/gmail/nossr50/metadata/MobMetadataService.java b/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java similarity index 83% rename from src/main/java/com/gmail/nossr50/metadata/MobMetadataService.java rename to src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java index e78b056c9..4e0ad1924 100644 --- a/src/main/java/com/gmail/nossr50/metadata/MobMetadataService.java +++ b/src/main/java/com/gmail/nossr50/util/MobMetadataUtils.java @@ -1,9 +1,8 @@ -package com.gmail.nossr50.metadata; +package com.gmail.nossr50.util; import com.gmail.nossr50.api.exceptions.IncompleteNamespacedKeyRegister; import com.gmail.nossr50.config.PersistentDataConfig; -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.MetadataConstants; +import com.gmail.nossr50.metadata.MobMetaFlagType; import org.bukkit.NamespacedKey; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; @@ -15,17 +14,19 @@ import java.util.EnumMap; import java.util.HashSet; import java.util.WeakHashMap; -import static com.gmail.nossr50.metadata.MetadataService.*; +import static com.gmail.nossr50.util.MetadataService.*; //TODO: Use SpawnReason where appropriate instead of MobMetaFlagType -public class MobMetadataService { - private final @NotNull WeakHashMap> mobRegistry; //transient data - private final @NotNull EnumMap mobFlagKeyMap; //used for persistent data - private final @NotNull mcMMO pluginRef; - private boolean isUsingPersistentData = false; +public final class MobMetadataUtils { + private static final @NotNull WeakHashMap> mobRegistry; //transient data + private static final @NotNull EnumMap mobFlagKeyMap; //used for persistent data + private static boolean isUsingPersistentData = false; - public MobMetadataService(@NotNull mcMMO pluginRef) { - this.pluginRef = pluginRef; + private MobMetadataUtils() { + // private ctor + } + + static { mobFlagKeyMap = new EnumMap<>(MobMetaFlagType.class); mobRegistry = new WeakHashMap<>(); initMobFlagKeyMap(); @@ -40,7 +41,7 @@ public class MobMetadataService { * Registers the namespaced keys required by the API (CB/Spigot) * Used primarily for persistent data */ - private void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister { + private static void initMobFlagKeyMap() throws IncompleteNamespacedKeyRegister { for (MobMetaFlagType mobMetaFlagType : MobMetaFlagType.values()) { switch (mobMetaFlagType) { case MOB_SPAWNER_MOB -> mobFlagKeyMap.put(mobMetaFlagType, NSK_MOB_SPAWNER_MOB); @@ -63,7 +64,7 @@ public class MobMetadataService { * * @return true if the mob has metadata values for target {@link MobMetaFlagType} */ - public boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static boolean hasMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { return livingEntity.getPersistentDataContainer().has(mobFlagKeyMap.get(flag), PersistentDataType.BYTE); } else { @@ -82,7 +83,7 @@ public class MobMetadataService { * * @return true if the mob has any mcMMO mob related metadata values */ - public boolean hasMobFlags(@NotNull LivingEntity livingEntity) { + public static boolean hasMobFlags(@NotNull LivingEntity livingEntity) { if (isUsingPersistentData) { for (MobMetaFlagType metaFlagType : MobMetaFlagType.values()) { if (hasMobFlag(metaFlagType, livingEntity)) @@ -102,7 +103,7 @@ public class MobMetadataService { * @param sourceEntity entity to copy from * @param targetEntity entity to copy to */ - public void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) { + public static void addMobFlags(@NotNull LivingEntity sourceEntity, @NotNull LivingEntity targetEntity) { if (!hasMobFlags(sourceEntity)) return; @@ -125,7 +126,7 @@ public class MobMetadataService { * @param flag the desired flag to assign * @param livingEntity the target living entity */ - public void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static void flagMetadata(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { if (!hasMobFlag(flag, livingEntity)) { PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer(); @@ -144,7 +145,7 @@ public class MobMetadataService { * @param flag desired flag to remove * @param livingEntity the target living entity */ - public void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { + public static void removeMobFlag(@NotNull MobMetaFlagType flag, @NotNull LivingEntity livingEntity) { if (PersistentDataConfig.getInstance().isMobPersistent(flag)) { if (hasMobFlag(flag, livingEntity)) { PersistentDataContainer persistentDataContainer = livingEntity.getPersistentDataContainer(); @@ -165,7 +166,7 @@ public class MobMetadataService { * * @param livingEntity target entity */ - public void removeMobFlags(@NotNull LivingEntity livingEntity) { + public static void removeMobFlags(@NotNull LivingEntity livingEntity) { if (isUsingPersistentData) { for (MobMetaFlagType flag : MobMetaFlagType.values()) { removeMobFlag(flag, livingEntity); diff --git a/src/main/java/com/gmail/nossr50/util/ModManager.java b/src/main/java/com/gmail/nossr50/util/ModManager.java index 19e1202ed..f70e356dd 100644 --- a/src/main/java/com/gmail/nossr50/util/ModManager.java +++ b/src/main/java/com/gmail/nossr50/util/ModManager.java @@ -215,8 +215,7 @@ public class ModManager { catch (Exception e) { if (e instanceof NoSuchFieldException || e instanceof IllegalArgumentException || e instanceof IllegalAccessException) { customEntity = customEntityClassMap.get(entity.getClass().getName()); - } - else { + } else { e.printStackTrace(); } } @@ -256,8 +255,7 @@ public class ModManager { catch (Exception e) { if (e instanceof NoSuchFieldException || e instanceof IllegalArgumentException || e instanceof IllegalAccessException) { className = entity.getClass().getName(); - } - else { + } else { e.printStackTrace(); } } diff --git a/src/main/java/com/gmail/nossr50/util/Permissions.java b/src/main/java/com/gmail/nossr50/util/Permissions.java index 6dcd9b800..03fcae47a 100644 --- a/src/main/java/com/gmail/nossr50/util/Permissions.java +++ b/src/main/java/com/gmail/nossr50/util/Permissions.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.commands.party.PartySubcommandType; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.ItemType; import com.gmail.nossr50.datatypes.skills.MaterialType; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; @@ -17,6 +18,7 @@ import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.PluginManager; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.Locale; @@ -171,10 +173,19 @@ public final class Permissions { } public static boolean vanillaXpBoost(Permissible permissible, PrimarySkillType skill) { return permissible.hasPermission("mcmmo.ability." + skill.toString().toLowerCase(Locale.ENGLISH) + ".vanillaxpboost"); } - public static boolean isSubSkillEnabled(Permissible permissible, SubSkillType subSkillType) { + public static boolean isSubSkillEnabled(@Nullable Permissible permissible, @NotNull SubSkillType subSkillType) { + if (permissible == null) + return false; return permissible.hasPermission(subSkillType.getPermissionNodeAddress()); } + public static boolean isSubSkillEnabled(@Nullable McMMOPlayer permissible, @NotNull SubSkillType subSkillType) { + if (permissible == null) + return false; + + return isSubSkillEnabled(permissible.getPlayer(), subSkillType); + } + /* ACROBATICS */ public static boolean dodge(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.dodge"); } public static boolean gracefulRoll(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.acrobatics.gracefulroll"); } @@ -185,7 +196,6 @@ public final class Permissions { public static boolean concoctions(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.alchemy.concoctions"); } /* ARCHERY */ - public static boolean explosiveShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.explosiveshot"); } public static boolean arrowRetrieval(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.trackarrows"); } public static boolean daze(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.archery.daze"); } @@ -233,19 +243,15 @@ public final class Permissions { public static boolean treeFeller(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.woodcutting.treefeller"); } /* CROSSBOWS */ - public static boolean superShotgun(Permissible permissible) { - return permissible.hasPermission("mcmmo.ability.crossbows.supershotgun"); - } public static boolean trickShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.crossbows.trickshot"); } public static boolean poweredShot(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.crossbows.poweredshot"); } /* TRIDENTS */ - public static boolean tridentsSuper(Permissible permissible) { - return false; - // return permissible.hasPermission("mcmmo.ability.tridents.superability"); - } public static boolean tridentsLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.tridents.superability"); } + /* MACES */ + public static boolean macesLimitBreak(Permissible permissible) { return permissible.hasPermission("mcmmo.ability.maces.limitbreak"); } + /* * PARTY */ diff --git a/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java new file mode 100644 index 000000000..6981644b3 --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionCompatibilityType.java @@ -0,0 +1,6 @@ +package com.gmail.nossr50.util; + +public enum PotionCompatibilityType { + PRE_1_20_5, + MODERN +} diff --git a/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java b/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java new file mode 100644 index 000000000..706cc8c9f --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionEffectUtil.java @@ -0,0 +1,92 @@ +package com.gmail.nossr50.util; + +import org.bukkit.potion.PotionEffectType; + +/** + * This util class is responsible for mapping the correct potion effect types for the server version. + * This is necessary because the potion effect types have changed between versions. + * This util class will provide the correct potion effect types for the server version. + */ +final public class PotionEffectUtil { + private static final PotionEffectType haste; + private static final PotionEffectType nausea; + + static { + haste = findHastePotionEffectType(); + nausea = findNauseaPotionEffectType(); + } + + private PotionEffectUtil() { + // Utility class + } + + private static PotionEffectType findNauseaPotionEffectType() { + if (getNauseaLegacy() != null) { + return getNauseaLegacy(); + } else { + return getNauseaModern(); + } + } + + private static PotionEffectType getNauseaModern() { + try { + return (PotionEffectType) PotionEffectType.class.getField("NAUSEA").get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + return null; + } + } + + private static PotionEffectType getNauseaLegacy() { + try { + Object potionEffectTypeWrapper = PotionEffectType.class.getField("CONFUSION").get(null); + return (PotionEffectType) potionEffectTypeWrapper; + } catch (IllegalAccessException | NoSuchFieldException e) { + return null; + } + } + + private static PotionEffectType findHastePotionEffectType() { + if (getHasteLegacy() != null) { + return getHasteLegacy(); + } else if (getHasteModern() != null) { + return getHasteModern(); + } else { + throw new IllegalStateException("Unable to find the Haste PotionEffectType"); + } + } + + private static PotionEffectType getHasteLegacy() { + try { + Object potionEffectTypeWrapper = PotionEffectType.class.getField("FAST_DIGGING").get(null); + return (PotionEffectType) potionEffectTypeWrapper; + } catch (IllegalAccessException | NoSuchFieldException e) { + return null; + } + } + + private static PotionEffectType getHasteModern() { + try { + return (PotionEffectType) PotionEffectType.class.getField("HASTE").get(null); + } catch (NoSuchFieldException | IllegalAccessException e) { + return null; + } + } + + /** + * Get the Haste potion effect type. + * This will return the correct potion effect type for the server version. + * @return The Haste potion effect type. + */ + public static PotionEffectType getHastePotionEffectType() { + return haste; + } + + /** + * Get the Nausea potion effect type. + * This will return the correct potion effect type for the server version. + * @return The Nausea potion effect type. + */ + public static PotionEffectType getNauseaPotionEffectType() { + return nausea; + } +} diff --git a/src/main/java/com/gmail/nossr50/util/PotionUtil.java b/src/main/java/com/gmail/nossr50/util/PotionUtil.java new file mode 100644 index 000000000..b369250fe --- /dev/null +++ b/src/main/java/com/gmail/nossr50/util/PotionUtil.java @@ -0,0 +1,544 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.potion.PotionType; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PotionUtil { + // Some of the old potion types got renamed, our configs can still contain these old names + private static final Map legacyPotionTypes = new HashMap<>(); + private static final Method methodPotionTypeGetKey; + private static final Method methodPotionTypeGetEffectType; + private static final Method methodPotionTypeGetPotionEffects; + private static final Method methodPotionDataIsUpgraded; + private static final Method methodPotionDataIsExtended; + private static final Method methodPotionDataGetType; + private static final Method methodPotionMetaGetBasePotionData; + private static final Method methodPotionMetaSetBasePotionData; + private static final Method methodPotionMetaGetBasePotionType; + private static final Method methodPotionMetaSetBasePotionType; + private static final Class potionDataClass; + + public static final String STRONG = "STRONG"; + public static final String LONG = "LONG"; + public static final String WATER_POTION_TYPE_STR = "WATER"; + + private static final PotionCompatibilityType COMPATIBILITY_MODE; + + static { + potionDataClass = getPotionDataClass(); + // Uncraftable doesn't exist in modern versions + // It served as a potion that didn't craft into anything else so it didn't conflict with vanilla systems + // Instead we will use Mundane, which doesn't make anything in vanilla systems + legacyPotionTypes.put("UNCRAFTABLE", "MUNDANE"); + legacyPotionTypes.put("JUMP", "LEAPING"); + legacyPotionTypes.put("SPEED", "SWIFTNESS"); + legacyPotionTypes.put("INSTANT_HEAL", "HEALING"); + legacyPotionTypes.put("INSTANT_DAMAGE", "HARMING"); + legacyPotionTypes.put("REGEN", "REGENERATION"); + methodPotionTypeGetKey = getKeyMethod(); + methodPotionDataIsUpgraded = getPotionDataIsUpgraded(); + methodPotionDataIsExtended = getPotionDataIsExtended(); + methodPotionMetaGetBasePotionData = getGetBasePotionDataMethod(); + methodPotionMetaGetBasePotionType = getGetBasePotionTypeMethod(); + methodPotionMetaSetBasePotionType = getMethodPotionMetaSetBasePotionType(); + methodPotionDataGetType = getPotionDataGetTypeMethod(); + methodPotionTypeGetEffectType = getPotionTypeEffectTypeMethod(); + methodPotionTypeGetPotionEffects = getPotionTypeGetPotionEffectsMethod(); + methodPotionMetaSetBasePotionData = setBasePotionData(); + + if (potionDataClass != null + && !mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 20, 5)) { + COMPATIBILITY_MODE = PotionCompatibilityType.PRE_1_20_5; + } else { + COMPATIBILITY_MODE = PotionCompatibilityType.MODERN; + } + } + + /** + * Derive a potion from a partial name, and whether it should be upgraded or extended. + * @param partialName potion type as a string, can be a substring of the potion type but must match exactly + * @return The potion type + */ + public static PotionType matchPotionType(String partialName, boolean isUpgraded, boolean isExtended) { + // updatedName = convertUpgradedOrExtended(updatedName, isUpgraded, isExtended); + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return matchLegacyPotionType(partialName); + } else { + String updatedName = convertLegacyNames(partialName).toUpperCase(); + return Arrays.stream(PotionType.values()) + .filter(potionType -> getKeyGetKey(potionType).toUpperCase().contains(updatedName)) + .filter(potionType -> !isUpgraded || potionType.name().toUpperCase().contains(STRONG)) + .filter(potionType -> !isExtended || potionType.name().toUpperCase().contains(LONG)) + .findAny().orElse(null); + } + } + + /** + * Legacy matching for {@link PotionType} + * + * @param name The partial name of the potion + * @return The potion type + */ + private static PotionType matchLegacyPotionType(String name) { + return Arrays.stream(PotionType.values()) + .filter(potionType -> getKeyGetKey(potionType).equalsIgnoreCase(name) + || getKeyGetKey(potionType).equalsIgnoreCase(convertLegacyNames(name)) + || potionType.name().equalsIgnoreCase(name) + || potionType.name().equalsIgnoreCase(convertLegacyNames(name))) + .findAny().orElse(null); + } + + private static String convertUpgradedOrExtended(String potionType, boolean isUpgraded, boolean isExtended) { + if (isUpgraded) { + potionType = STRONG + "_" + potionType; + } + if (isExtended) { + potionType = LONG + "_" + potionType; + } + return potionType; + } + + public static String getKeyGetKey(PotionType potionType) { + try { + if (getKeyMethod() != null) { + NamespacedKey key = (NamespacedKey) methodPotionTypeGetKey.invoke(potionType); + return key.getKey(); + } else { + return potionType.name(); + } + } catch (InvocationTargetException | IllegalAccessException e) { + mcMMO.p.getLogger().warning("Failed to get potion key for " + potionType.name()); + return potionType.name(); + } + } + + private static Class getPotionDataClass() { + try { + return Class.forName("org.bukkit.potion.PotionData"); + } catch (ClassNotFoundException e) { + return null; + } + } + + /** + * Older versions of Spigot do not have getKey() in PotionType + * We need to check for the existence of this method before calling it + * @return The getKey method + */ + private static @Nullable Method getKeyMethod() { + try { + return PotionType.class.getMethod("getKey"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static @Nullable Method setBasePotionData() { + try { + return PotionMeta.class.getMethod("setBasePotionData", potionDataClass); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getMethodPotionMetaSetBasePotionType() { + try { + return PotionMeta.class.getMethod("setBasePotionType", PotionType.class); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getSetBasePotionData() { + try { + return PotionMeta.class.getMethod("setBasePotionData", potionDataClass); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static @Nullable Method getPotionDataIsUpgraded() { + try { + // TODO: Needed? + final Class clazz = Class.forName("org.bukkit.potion.PotionData"); + return clazz.getMethod("isUpgraded"); + } catch (NoSuchMethodException | ClassNotFoundException e) { + return null; + } + } + + private static @Nullable Method getPotionDataIsExtended() { + try { + // TODO: Needed? + final Class clazz = Class.forName("org.bukkit.potion.PotionData"); + return clazz.getMethod("isExtended"); + } catch (NoSuchMethodException | ClassNotFoundException e) { + return null; + } + } + + /** + * Newer versions of Spigot do not have getBasePotionData() in PotionMeta + * + * @return the getBasePotionData method, or null if it does not exist + */ + private static @Nullable Method getGetBasePotionDataMethod() { + try { + return PotionMeta.class.getMethod("getBasePotionData"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getGetBasePotionTypeMethod() { + try { + return PotionMeta.class.getMethod("getBasePotionType"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getPotionDataGetTypeMethod() { + try { + final Class clazz = Class.forName("org.bukkit.potion.PotionData"); + return clazz.getMethod("getType"); + } catch (NoSuchMethodException | ClassNotFoundException e) { + return null; + } + } + + private static Method getPotionTypeEffectTypeMethod() { + try { + return PotionType.class.getMethod("getEffectType"); + } catch (NoSuchMethodException e) { + return null; + } + } + + private static Method getPotionTypeGetPotionEffectsMethod() { + try { + return PotionType.class.getMethod("getPotionEffects"); + } catch (NoSuchMethodException e) { + return null; + } + } + + public static String convertPotionConfigName(String legacyName) { + String replacementName = legacyName; + + // Remove generated potions.yml config naming convention + if (replacementName.contains("POTION_OF_")) { + replacementName = replacementName.replace("POTION_OF_", ""); + } + + if (replacementName.contains("_II")) { + replacementName = replacementName.replace("_II", ""); + replacementName = "STRONG_" + replacementName; + } else if (replacementName.contains("_EXTENDED")) { + replacementName = replacementName.replace("_EXTENDED", ""); + replacementName = "LONG_" + replacementName; + } + return replacementName; + } + + public static String convertLegacyNames(String legacyPotionType) { + String modernized = legacyPotionType; + // check for legacy names + for (var key : legacyPotionTypes.keySet()) { + if (modernized.contains(key)) { + // Replace the legacy name with the new name + modernized = modernized.replace(key, legacyPotionTypes.get(key)); + break; + } + } + return modernized; + } + + public static boolean hasLegacyName(String potionType) { + for (var key : legacyPotionTypes.keySet()) { + if (potionType.contains(key)) { + return true; + } + } + return false; + } + + public static boolean isStrong(PotionMeta potionMeta) { + if (methodPotionMetaGetBasePotionData == null) { + return isStrongModern(potionMeta); + } else { + return isStrongLegacy(potionMeta); + } + + } + + public static boolean isLong(PotionMeta potionMeta) { + if (methodPotionMetaGetBasePotionData == null) { + return isLongModern(potionMeta); + } else { + return isLongLegacy(potionMeta); + } + } + + private static boolean isLongLegacy(PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + return (boolean) methodPotionDataIsExtended.invoke(potionData); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static boolean isLongModern(PotionMeta potionMeta) { + try { + return getModernPotionTypeKey(potionMeta).getKey().startsWith(LONG); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static boolean isStrongLegacy(PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + return (boolean) methodPotionDataIsUpgraded.invoke(potionData); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static boolean isStrongModern(PotionMeta potionMeta) { + try { + return getModernPotionTypeKey(potionMeta).getKey().startsWith(STRONG); + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + private static NamespacedKey getModernPotionTypeKey(PotionMeta potionMeta) throws IllegalAccessException, InvocationTargetException { + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); + return (NamespacedKey) methodPotionTypeGetKey.invoke(potionType); + } + + public static boolean isPotionJustWater(PotionMeta potionMeta) { + return isPotionTypeWater(potionMeta) + && !hasBasePotionEffects(potionMeta) + && potionMeta.getCustomEffects().isEmpty(); + } + + public static boolean isPotionTypeWater(@NotNull PotionMeta potionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return isPotionTypeWaterLegacy(potionMeta); + } else { + return isPotionTypeWaterModern(potionMeta); + } + } + + public static boolean isPotionType(@NotNull PotionMeta potionMeta, String potionType) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return isPotionTypeLegacy(potionMeta, potionType); + } else { + return isPotionTypeModern(potionMeta, potionType); + } + } + + public static boolean isPotionTypeWithoutEffects(@NotNull PotionMeta potionMeta, String potionType) { + return isPotionType(potionMeta, potionType) + && !hasBasePotionEffects(potionMeta) + && potionMeta.getCustomEffects().isEmpty(); + } + + private static boolean isPotionTypeModern(@NotNull PotionMeta potionMeta, String potionType) { + try { + return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(potionType); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean isPotionTypeLegacy(@NotNull PotionMeta potionMeta, String potionType) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + PotionType potionTypeObj = (PotionType) methodPotionDataGetType.invoke(potionData); + return potionTypeObj.name().equalsIgnoreCase(potionType); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean isPotionTypeWaterLegacy(@NotNull PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + return potionType.name().equalsIgnoreCase(WATER_POTION_TYPE_STR) + || PotionType.valueOf(WATER_POTION_TYPE_STR) == potionType; + } catch (InvocationTargetException | IllegalAccessException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean isPotionTypeWaterModern(@NotNull PotionMeta potionMeta) { + try { + return getModernPotionTypeKey(potionMeta).getKey().equalsIgnoreCase(WATER_POTION_TYPE_STR); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + public static boolean samePotionType(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return samePotionTypeLegacy(potionMeta, otherPotionMeta); + } else { + return samePotionTypeModern(potionMeta, otherPotionMeta); + } + } + + private static boolean samePotionTypeLegacy(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + Object otherPotionData = methodPotionMetaGetBasePotionData.invoke(otherPotionMeta); + PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke(otherPotionData); + return potionType == otherPotionType; + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean samePotionTypeModern(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + try { + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); + PotionType otherPotionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(otherPotionMeta); + return potionType == otherPotionType; + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + + public static boolean samePotionEffects(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return true; + } else { + return samePotionEffectsModern(potionMeta, otherPotionMeta); + } + } + + private static boolean samePotionEffectsModern(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + return potionMeta.getCustomEffects().equals(otherPotionMeta.getCustomEffects()); + } + + public static boolean hasBasePotionEffects(PotionMeta potionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.PRE_1_20_5) { + return hasBasePotionEffectsLegacy(potionMeta); + } else { + return hasBasePotionEffectsModern(potionMeta); + } + } + + private static boolean hasBasePotionEffectsLegacy(PotionMeta potionMeta) { + try { + Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + return methodPotionTypeGetEffectType.invoke(potionType) != null; + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + private static boolean hasBasePotionEffectsModern(PotionMeta potionMeta) { + try { + PotionType potionType = (PotionType) methodPotionMetaGetBasePotionType.invoke(potionMeta); + List potionEffectTypeList = (List) methodPotionTypeGetPotionEffects.invoke(potionType); + return potionEffectTypeList != null && !potionEffectTypeList.isEmpty(); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + /** + * Set the base potion type of a potion meta. + * Note that extended/upgraded are ignored in 1.20.5 and later. + * + * @param potionMeta the potion meta + * @param extended true if the potion is extended + * @param upgraded true if the potion is upgraded + */ + public static void setBasePotionType(PotionMeta potionMeta, PotionType potionType, boolean extended, boolean upgraded) { + if (methodPotionMetaSetBasePotionType == null) { + setBasePotionTypeLegacy(potionMeta, potionType, extended, upgraded); + } else { + setBasePotionTypeModern(potionMeta, potionType); + } + } + + public static void setUpgradedAndExtendedProperties(PotionType potionType, PotionMeta potionMeta, + boolean isUpgraded, boolean isExtended) { + if (potionDataClass == null || mcMMO.getCompatibilityManager().getMinecraftGameVersion().isAtLeast(1, 20, 5)) { + return; + } + + try { + final Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) + .newInstance(potionType, isExtended, isUpgraded); + methodPotionMetaSetBasePotionData.invoke(potionMeta, potionData); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException + | NoSuchMethodException ex) { + throw new RuntimeException(ex); + } + } + + private static void setBasePotionTypeLegacy(PotionMeta potionMeta, PotionType potionType, boolean extended, + boolean upgraded) { + try { + Object potionData = potionDataClass.getConstructor(PotionType.class, boolean.class, boolean.class) + .newInstance(potionType, extended, upgraded); + methodPotionMetaSetBasePotionData.invoke(potionMeta, potionData); + } catch (IllegalAccessException | InvocationTargetException | InstantiationException | NoSuchMethodException ex) { + throw new RuntimeException(ex); + } + } + + private static void setBasePotionTypeModern(PotionMeta potionMeta, PotionType potionType) { + try { + methodPotionMetaSetBasePotionType.invoke(potionMeta, potionType); + } catch (IllegalAccessException | InvocationTargetException ex) { + throw new RuntimeException(ex); + } + } + + public static boolean isPotionDataEqual(PotionMeta potionMeta, PotionMeta otherPotionMeta) { + if (COMPATIBILITY_MODE == PotionCompatibilityType.MODERN) { + return true; // we don't compare data on newer versions + } else { + try { + final Object potionData = methodPotionMetaGetBasePotionData.invoke(potionMeta); + final Object otherPotionData = methodPotionMetaGetBasePotionData.invoke(otherPotionMeta); + final PotionType potionType = (PotionType) methodPotionDataGetType.invoke(potionData); + final PotionType otherPotionType = (PotionType) methodPotionDataGetType.invoke(otherPotionData); + if (potionType != otherPotionType) { + return false; + } + if (methodPotionDataIsExtended.invoke(potionData) != methodPotionDataIsExtended.invoke(otherPotionData)) { + return false; + } + if (methodPotionDataIsUpgraded.invoke(potionData) != methodPotionDataIsUpgraded.invoke(otherPotionData)) { + return false; + } + return true; + } catch (IllegalAccessException | InvocationTargetException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java index 8b258d03a..c463077db 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java +++ b/src/main/java/com/gmail/nossr50/util/TransientEntityTracker.java @@ -1,7 +1,6 @@ package com.gmail.nossr50.util; import com.gmail.nossr50.datatypes.skills.subskills.taming.CallOfTheWildType; -import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.skills.taming.TrackedTamingEntity; import com.gmail.nossr50.util.player.NotificationManager; import com.gmail.nossr50.util.skills.ParticleEffectUtils; @@ -18,6 +17,8 @@ import org.jetbrains.annotations.Nullable; import java.util.*; +import static com.gmail.nossr50.util.MobMetadataUtils.removeMobFlags; + public class TransientEntityTracker { //These two are updated in step with each other private final @NotNull HashMap>> perPlayerTransientEntityMap; @@ -145,7 +146,7 @@ public class TransientEntityTracker { private synchronized @Nullable HashSet getTrackedEntities(@NotNull UUID playerUUID, @NotNull CallOfTheWildType callOfTheWildType) { HashMap> playerEntityMap = getPlayerTrackedEntityMap(playerUUID); - if(playerEntityMap == null) + if (playerEntityMap == null) return null; return playerEntityMap.get(callOfTheWildType); @@ -194,12 +195,12 @@ public class TransientEntityTracker { HashSet trackedEntities = getTrackedEntities(uuid, callOfTheWildType); - if(trackedEntities == null) + if (trackedEntities == null) continue; Iterator iterator = trackedEntities.iterator(); while (iterator.hasNext()) { - if(iterator.next().getLivingEntity().equals(livingEntity)) { + if (iterator.next().getLivingEntity().equals(livingEntity)) { iterator.remove(); return; } @@ -218,7 +219,7 @@ public class TransientEntityTracker { ArrayList matchingEntities = new ArrayList<>(); for(LivingEntity livingEntity : getChunkLookupCache()) { - if(livingEntity.getLocation().getChunk().equals(chunk)) { + if (livingEntity.getLocation().getChunk().equals(chunk)) { matchingEntities.add(livingEntity); } } @@ -236,7 +237,7 @@ public class TransientEntityTracker { public synchronized int getAmountCurrentlySummoned(@NotNull UUID playerUUID, @NotNull CallOfTheWildType callOfTheWildType) { HashSet trackedEntities = getTrackedEntities(playerUUID, callOfTheWildType); - if(trackedEntities == null) + if (trackedEntities == null) return 0; return trackedEntities.size(); @@ -251,7 +252,7 @@ public class TransientEntityTracker { */ public synchronized void removeSummon(@NotNull LivingEntity livingEntity, @Nullable Player player, boolean timeExpired) { //Kill the summon & remove it - if(livingEntity.isValid()) { + if (livingEntity.isValid()) { livingEntity.setHealth(0); //Should trigger entity death events livingEntity.remove(); @@ -263,8 +264,8 @@ public class TransientEntityTracker { } //Inform player of summon death - if(player != null && player.isOnline()) { - if(timeExpired) { + if (player != null && player.isOnline()) { + if (timeExpired) { NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.TimeExpired", StringUtils.getPrettyEntityTypeString(livingEntity.getType())); } else { NotificationManager.sendPlayerInformationChatOnly(player, "Taming.Summon.COTW.Removed", StringUtils.getPrettyEntityTypeString(livingEntity.getType())); @@ -273,7 +274,7 @@ public class TransientEntityTracker { } //Remove our metadata - mcMMO.getMetadataService().getMobMetadataService().removeMobFlags(livingEntity); + removeMobFlags(livingEntity); //Clean from trackers unregisterEntity(livingEntity); @@ -300,7 +301,7 @@ public class TransientEntityTracker { for(CallOfTheWildType callOfTheWildType : CallOfTheWildType.values()) { HashSet trackedEntities = getTrackedEntities(playerUUID, callOfTheWildType); - if(trackedEntities == null) { + if (trackedEntities == null) { continue; } diff --git a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java index 8b21e9d1a..c7f1e335a 100644 --- a/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java +++ b/src/main/java/com/gmail/nossr50/util/TransientMetadataTools.java @@ -4,6 +4,8 @@ import com.gmail.nossr50.mcMMO; import org.bukkit.entity.LivingEntity; import org.jetbrains.annotations.NotNull; +import static com.gmail.nossr50.util.MobMetadataUtils.removeMobFlags; + public class TransientMetadataTools { private final mcMMO pluginRef; @@ -25,16 +27,16 @@ public class TransientMetadataTools { } //Gets assigned to endermen, potentially doesn't get cleared before this point - if(entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) { + if (entity.hasMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK)) { entity.removeMetadata(MetadataConstants.METADATA_KEY_TRAVELING_BLOCK, pluginRef); } //Cleanup mob metadata - mcMMO.getMetadataService().getMobMetadataService().removeMobFlags(entity); + removeMobFlags(entity); //TODO: This loop has some redundancy, this whole method needs to be rewritten for(String key : MetadataConstants.MOB_METADATA_KEYS) { - if(entity.hasMetadata(key)) { + if (entity.hasMetadata(key)) { entity.removeMetadata(key, pluginRef); } } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java b/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java index bdee4a3b9..a25f60beb 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStore.java @@ -118,8 +118,7 @@ public class BitSetChunkStore implements ChunkStore { return world.getMinHeight(); } - private static int getWorldMax(@NotNull UUID worldUid) - { + private static int getWorldMax(@NotNull UUID worldUid) { World world = Bukkit.getWorld(worldUid); // Not sure how this case could come up, but might as well handle it gracefully. Loading a chunkstore for an unloaded world? @@ -181,8 +180,7 @@ public class BitSetChunkStore implements ChunkStore { if (currentWorldMin > worldMin) stored = stored.get(currentWorldMin, stored.length()); // Because BitSet's aren't fixed size, a "substring" operation is equivalent to a left shift // Right shift store if world min has expanded - if (currentWorldMin < worldMin) - { + if (currentWorldMin < worldMin) { int offset = (worldMin - currentWorldMin) * 16 * 16; // We are adding this many bits to the front // This isn't the most efficient way to do this, however, its a rare case to occur, and in the grand scheme of things, the small performance we could gain would cost us significant reduced readability of the code BitSet shifted = new BitSet(); @@ -207,13 +205,12 @@ public class BitSetChunkStore implements ChunkStore { inputStream.mark(2); short magicNumber = inputStream.readShort(); - if (magicNumber == ObjectStreamConstants.STREAM_MAGIC) // Java serializable, use legacy serialization - { + // Java serializable, use legacy serialization + if (magicNumber == ObjectStreamConstants.STREAM_MAGIC) { // "Un-read" the magic number for Serializables, they need it to still be in the stream - if (inputStream.markSupported()) + if (inputStream.markSupported()) { inputStream.reset(); // Pretend we never read those bytes - else - { + } else { // Creates a new stream with the two magic number bytes and then the rest of the original stream... Java is so dumb. I just wanted to look at two bytes. PushbackInputStream pushbackInputStream = new PushbackInputStream(inputStream, 2); pushbackInputStream.unread((magicNumber) & 0xFF); @@ -221,9 +218,8 @@ public class BitSetChunkStore implements ChunkStore { inputStream = new DataInputStream(pushbackInputStream); } return new LegacyDeserializationInputStream(inputStream).readLegacyChunkStore(); - } - else if (magicNumber == STREAM_MAGIC) // Pure bytes format - { + } else if (magicNumber == STREAM_MAGIC) { + // Pure bytes format return BitSetChunkStore.deserialize(inputStream); } throw new IOException("Bad Data Format"); @@ -238,8 +234,7 @@ public class BitSetChunkStore implements ChunkStore { // Handles loading the old serialized class private static class LegacyDeserializationInputStream extends ObjectInputStream { - private static class LegacyChunkStoreDeserializer implements Serializable - { + private static class LegacyChunkStoreDeserializer implements Serializable { private static final long serialVersionUID = -1L; private int cx; @@ -270,8 +265,7 @@ public class BitSetChunkStore implements ChunkStore { worldMax = store[0][0].length; } - public @NotNull BitSetChunkStore convert() - { + public @NotNull BitSetChunkStore convert() { int currentWorldMin = getWorldMin(worldUid); int currentWorldMax = getWorldMax(worldUid); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java index 5f38022d5..203c71e71 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/HashChunkManager.java @@ -21,8 +21,7 @@ public class HashChunkManager implements ChunkManager { @Override public synchronized void closeAll() { // Save all dirty chunkstores - for (ChunkStore chunkStore : chunkMap.values()) - { + for (ChunkStore chunkStore : chunkMap.values()) { if (!chunkStore.isDirty()) continue; World world = Bukkit.getWorld(chunkStore.getWorldId()); @@ -113,8 +112,8 @@ public class HashChunkManager implements ChunkManager { CoordinateKey regionKey = toRegionKey(world.getUID(), cx, cz); HashSet chunkKeys = chunkUsageMap.get(regionKey); chunkKeys.remove(chunkKey); // remove from region file in-use set - if (chunkKeys.isEmpty()) // If it was last chunk in region, close the region file and remove it from memory - { + // If it was last chunk in region, close the region file and remove it from memory + if (chunkKeys.isEmpty()) { chunkUsageMap.remove(regionKey); regionMap.remove(regionKey).close(); } @@ -152,7 +151,7 @@ public class HashChunkManager implements ChunkManager { } } - private synchronized boolean isTrue(int x, int y, int z, @NotNull World world) { + private synchronized boolean isIneligible(int x, int y, int z, @NotNull World world) { CoordinateKey chunkKey = blockCoordinateToChunkKey(world.getUID(), x, y, z); // Get chunk, load from file if necessary @@ -178,32 +177,42 @@ public class HashChunkManager implements ChunkManager { } @Override - public synchronized boolean isTrue(@NotNull Block block) { - return isTrue(block.getX(), block.getY(), block.getZ(), block.getWorld()); + public synchronized boolean isIneligible(@NotNull Block block) { + return isIneligible(block.getX(), block.getY(), block.getZ(), block.getWorld()); } @Override - public synchronized boolean isTrue(@NotNull BlockState blockState) { - return isTrue(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld()); + public synchronized boolean isIneligible(@NotNull BlockState blockState) { + return isIneligible(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld()); } @Override - public synchronized void setTrue(@NotNull Block block) { + public synchronized boolean isEligible(@NotNull Block block) { + return !isIneligible(block); + } + + @Override + public synchronized boolean isEligible(@NotNull BlockState blockState) { + return !isIneligible(blockState); + } + + @Override + public synchronized void setIneligible(@NotNull Block block) { set(block.getX(), block.getY(), block.getZ(), block.getWorld(), true); } @Override - public synchronized void setTrue(@NotNull BlockState blockState) { + public synchronized void setIneligible(@NotNull BlockState blockState) { set(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld(), true); } @Override - public synchronized void setFalse(@NotNull Block block) { + public synchronized void setEligible(@NotNull Block block) { set(block.getX(), block.getY(), block.getZ(), block.getWorld(), false); } @Override - public synchronized void setFalse(@NotNull BlockState blockState) { + public synchronized void setEligible(@NotNull BlockState blockState) { set(blockState.getX(), blockState.getY(), blockState.getZ(), blockState.getWorld(), false); } @@ -214,8 +223,7 @@ public class HashChunkManager implements ChunkManager { ChunkStore cStore = chunkMap.computeIfAbsent(chunkKey, k -> { // Load from file ChunkStore loaded = loadChunk(chunkKey.x, chunkKey.z, world); - if (loaded != null) - { + if (loaded != null) { chunkUsageMap.computeIfAbsent(toRegionKey(chunkKey.worldID, chunkKey.x, chunkKey.z), j -> new HashSet<>()).add(chunkKey); return loaded; } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java b/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java index 80f15699b..1e5f860fa 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/McMMOSimpleRegionFile.java @@ -181,8 +181,7 @@ public class McMMOSimpleRegionFile { int end = start + chunkNumSegments[index]; // If we are writing, assert we don't write over any in-use segments - if (inUse) - { + if (inUse) { int nextSetBit = segments.nextSetBit(start); if (nextSetBit != -1 && nextSetBit < end) throw new IllegalStateException("Attempting to overwrite an in-use segment"); diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java index 203376780..bc700b6e4 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/NullChunkManager.java @@ -17,24 +17,34 @@ public class NullChunkManager implements ChunkManager { public void unloadWorld(@NotNull World world) {} @Override - public boolean isTrue(@NotNull Block block) { + public boolean isIneligible(@NotNull Block block) { return false; } @Override - public boolean isTrue(@NotNull BlockState blockState) { + public boolean isIneligible(@NotNull BlockState blockState) { return false; } @Override - public void setTrue(@NotNull Block block) {} + public boolean isEligible(@NotNull Block block) { + return false; + } @Override - public void setTrue(@NotNull BlockState blockState) {} + public boolean isEligible(@NotNull BlockState blockState) { + return false; + } @Override - public void setFalse(@NotNull Block block) {} + public void setIneligible(@NotNull Block block) {} @Override - public void setFalse(@NotNull BlockState blockState) {} + public void setIneligible(@NotNull BlockState blockState) {} + + @Override + public void setEligible(@NotNull Block block) {} + + @Override + public void setEligible(@NotNull BlockState blockState) {} } diff --git a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java index e5428b0c1..8979e9125 100644 --- a/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java +++ b/src/main/java/com/gmail/nossr50/util/blockmeta/UserBlockTracker.java @@ -7,50 +7,140 @@ import org.jetbrains.annotations.NotNull; /** * Contains blockstore methods that are safe for external plugins to access. - * An instance can be retrieved via {@link mcMMO#getPlaceStore() mcMMO.getPlaceStore()} + * An instance can be retrieved via {@link mcMMO#getUserBlockTracker() mcMMO.getPlaceStore()} */ public interface UserBlockTracker { /** - * Check to see if a given block location is set to true + * Check to see if a given {@link Block} is ineligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. * - * @param block Block location to check - * @return true if the given block location is set to true, false if otherwise + * @param block Block to check + * @return true if the given block should not give rewards, false if otherwise */ - boolean isTrue(@NotNull Block block); + boolean isIneligible(@NotNull Block block); /** - * Check to see if a given BlockState location is set to true + * Check to see if a given {@link Block} is eligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * + * @param block Block to check + * @return true if the given block should give rewards, false if otherwise + */ + boolean isEligible(@NotNull Block block); + + /** + * Check to see if a given {@link BlockState} is eligible for rewards. + * This is a location-based lookup, and the other properties of the {@link BlockState} do not matter. * * @param blockState BlockState to check * @return true if the given BlockState location is set to true, false if otherwise */ - boolean isTrue(@NotNull BlockState blockState); + boolean isEligible(@NotNull BlockState blockState); /** - * Set a given block location to true + * Check to see if a given {@link BlockState} is ineligible for rewards. + * This is a location-based lookup, and the other properties of the {@link BlockState} do not matter. * - * @param block Block location to set + * @param blockState BlockState to check + * @return true if the given BlockState location is set to true, false if otherwise */ - void setTrue(@NotNull Block block); + boolean isIneligible(@NotNull BlockState blockState); + + /** + * Set a given {@link Block} as ineligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. + * + * @param block block whose location to set as ineligible + */ + void setIneligible(@NotNull Block block); /** * Set a given BlockState location to true * * @param blockState BlockState location to set */ - void setTrue(@NotNull BlockState blockState); + void setIneligible(@NotNull BlockState blockState); /** - * Set a given block location to false + * Set a given {@link Block} as eligible for rewards. + * This is a location-based lookup, and the other properties of the {@link Block} do not matter. * - * @param block Block location to set + * @param block block whose location to set as eligible */ - void setFalse(@NotNull Block block); + void setEligible(@NotNull Block block); /** * Set a given BlockState location to false * * @param blockState BlockState location to set */ - void setFalse(@NotNull BlockState blockState); + void setEligible(@NotNull BlockState blockState); + + /** + * Check to see if a given block location is set to true + * + * @param block Block location to check + * @return true if the given block location is set to true, false if otherwise + * @deprecated Use {@link #isIneligible(Block)} instead + */ + @Deprecated(since = "2.2.013") + default boolean isTrue(@NotNull Block block) { + return isIneligible(block); + } + + /** + * Check to see if a given BlockState location is set to true + * + * @param blockState BlockState to check + * @return true if the given BlockState location is set to true, false if otherwise + * @deprecated Use {@link #isIneligible(BlockState)} instead + */ + @Deprecated(since = "2.2.013") + default boolean isTrue(@NotNull BlockState blockState) { + return isIneligible(blockState); + } + + /** + * Set a given block location to true + * + * @param block Block location to set + * @deprecated Use {@link #setIneligible(Block)} instead + */ + @Deprecated(since = "2.2.013") + default void setTrue(@NotNull Block block) { + setIneligible(block); + } + + /** + * Set a given BlockState location to true + * + * @param blockState BlockState location to set + * @deprecated Use {@link #setIneligible(BlockState)} instead + */ + @Deprecated(since = "2.2.013") + default void setTrue(@NotNull BlockState blockState) { + setIneligible(blockState); + } + + /** + * Set a given block location to false + * + * @param block Block location to set + * @deprecated Use {@link #setEligible(Block)} instead + */ + @Deprecated(since = "2.2.013") + default void setFalse(@NotNull Block block) { + setEligible(block); + } + + /** + * Set a given BlockState location to false + * + * @param blockState BlockState location to set + * @deprecated Use {@link #setEligible(BlockState)} instead + */ + @Deprecated(since = "2.2.013") + default void setFalse(@NotNull BlockState blockState) { + setEligible(blockState); + } } diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java index 0946b4cc5..ced2cbf25 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandRegistrationManager.java @@ -33,6 +33,9 @@ public final class CommandRegistrationManager { private static void registerSkillCommands() { for (PrimarySkillType skill : PrimarySkillType.values()) { + if (skill == PrimarySkillType.MACES) + continue; + String commandName = skill.toString().toLowerCase(Locale.ENGLISH); String localizedName = mcMMO.p.getSkillTools().getLocalizedSkillName(skill).toLowerCase(Locale.ENGLISH); @@ -77,6 +80,10 @@ public final class CommandRegistrationManager { command.setExecutor(new HerbalismCommand()); break; + case MACES: + // command.setExecutor(new MacesCommand()); + break; + case MINING: command.setExecutor(new MiningCommand()); break; @@ -113,7 +120,7 @@ public final class CommandRegistrationManager { break; default: - break; + throw new IllegalStateException("Unexpected value: " + skill); } } } diff --git a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java index fcbd2fdbe..be38e4f9c 100644 --- a/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java +++ b/src/main/java/com/gmail/nossr50/util/commands/CommandUtils.java @@ -36,7 +36,7 @@ public final class CommandUtils { } public static boolean tooFar(CommandSender sender, Player target, boolean hasPermission) { - if(!target.isOnline() && !hasPermission) { + if (!target.isOnline() && !hasPermission) { sender.sendMessage(LocaleLoader.getString("Inspect.Offline")); return true; } else if (sender instanceof Player && !Misc.isNear(((Player) sender).getLocation(), target.getLocation(), mcMMO.p.getGeneralConfig().getInspectDistance()) && !hasPermission) { @@ -217,7 +217,7 @@ public final class CommandUtils { } private static void printGroupedSkillData(Player inspectTarget, CommandSender display, String header, List skillGroup) { - if(UserManager.getPlayer(inspectTarget) == null) + if (UserManager.getPlayer(inspectTarget) == null) return; PlayerProfile profile = UserManager.getPlayer(inspectTarget).getProfile(); @@ -265,8 +265,7 @@ public final class CommandUtils { if (matches.size() == 1) { partialName = matches.get(0); } - } - else { + } else { Player player = mcMMO.p.getServer().getPlayer(partialName); if (player != null) { diff --git a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java index 11d4a6d68..db6de7825 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java +++ b/src/main/java/com/gmail/nossr50/util/compat/CompatibilityManager.java @@ -23,7 +23,6 @@ import java.util.HashMap; * In 2.2 we are switching to modules and that will clean things up significantly * */ -//TODO: I need to delete this crap public class CompatibilityManager { private @NotNull HashMap supportedLayers; private boolean isFullyCompatibleServerSoftware = true; //true if all compatibility layers load successfully @@ -67,7 +66,7 @@ public class CompatibilityManager { } private void initMasterAnglerLayer() { - if(minecraftGameVersion.isAtLeast(1, 16, 3)) { + if (minecraftGameVersion.isAtLeast(1, 16, 3)) { masterAnglerCompatibility = new MasterAnglerCompatibilityLayer(); } else { masterAnglerCompatibility = null; @@ -75,7 +74,7 @@ public class CompatibilityManager { } private void initBungeeSerializerLayer() { - if(minecraftGameVersion.isAtLeast(1, 16, 0)) { + if (minecraftGameVersion.isAtLeast(1, 16, 0)) { bungeeSerializerCompatibilityLayer = new BungeeModernSerializerCompatibilityLayer(); } else { bungeeSerializerCompatibilityLayer = new BungeeLegacySerializerCompatibilityLayer(); @@ -86,13 +85,13 @@ public class CompatibilityManager { //TODO: move to text manager public void reportCompatibilityStatus(@NotNull CommandSender commandSender) { - if(isFullyCompatibleServerSoftware) { + if (isFullyCompatibleServerSoftware) { commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", "mcMMO is fully compatible with the currently running server software.")); } else { //TODO: Better messages for each incompatible layer for(CompatibilityType compatibilityType : CompatibilityType.values()) { - if(!supportedLayers.get(compatibilityType)) { + if (!supportedLayers.get(compatibilityType)) { commandSender.sendMessage(LocaleLoader.getString("mcMMO.Template.Prefix", LocaleLoader.getString("Compatibility.Layer.Unsupported", StringUtils.getCapitalized(compatibilityType.toString())))); } @@ -116,7 +115,7 @@ public class CompatibilityManager { private @NotNull NMSVersion determineNMSVersion() { //This bit here helps prevent mcMMO breaking if it isn't updated but the game continues to update - if(minecraftGameVersion.isAtLeast(1, 17, 0)) { + if (minecraftGameVersion.isAtLeast(1, 17, 0)) { return NMSVersion.NMS_1_17; } @@ -134,13 +133,13 @@ public class CompatibilityManager { case 16: if (minecraftGameVersion.getPatchVersion().asInt() == 1) { return NMSVersion.NMS_1_16_1; - } else if(minecraftGameVersion.getPatchVersion().asInt() == 2) { + } else if (minecraftGameVersion.getPatchVersion().asInt() == 2) { return NMSVersion.NMS_1_16_2; - } else if(minecraftGameVersion.getPatchVersion().asInt() == 3) { + } else if (minecraftGameVersion.getPatchVersion().asInt() == 3) { return NMSVersion.NMS_1_16_3; - } else if(minecraftGameVersion.getPatchVersion().asInt() == 4) { + } else if (minecraftGameVersion.getPatchVersion().asInt() == 4) { return NMSVersion.NMS_1_16_4; - } else if(minecraftGameVersion.getPatchVersion().asInt() >= 5) { + } else if (minecraftGameVersion.getPatchVersion().asInt() >= 5) { return NMSVersion.NMS_1_16_5; } case 17: @@ -159,7 +158,7 @@ public class CompatibilityManager { return masterAnglerCompatibility; } - public @Nullable MinecraftGameVersion getMinecraftGameVersion() { + public @NotNull MinecraftGameVersion getMinecraftGameVersion() { return minecraftGameVersion; } } diff --git a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java index 5b0026198..7a870c27a 100644 --- a/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java +++ b/src/main/java/com/gmail/nossr50/util/compat/layers/attackcooldown/PlayerAttackCooldownToolLayer.java @@ -37,15 +37,15 @@ // public PlayerAttackCooldownToolLayer(@NotNull NMSVersion nmsVersion) { // super(nmsVersion); // mcMMO.p.getLogger().info("Loading Compatibility Layer... (Player Attack Cooldown Exploit Prevention)"); -// if(!isCompatibleWithMinecraftVersion(nmsVersion)) { +// if (!isCompatibleWithMinecraftVersion(nmsVersion)) { // mcMMO.p.getLogger().severe("this version of mcMMO does not support NMS for this version of Minecraft, try updating mcMMO or updating Minecraft. Not all versions of Minecraft will have NMS support built into mcMMO."); // cbNMSVersionPath = ""; // } else { -// if(NMSConstants.getCraftBukkitVersionPath(nmsVersion) != null) { +// if (NMSConstants.getCraftBukkitVersionPath(nmsVersion) != null) { // cbNMSVersionPath = NMSConstants.getCraftBukkitVersionPath(nmsVersion); // noErrorsOnInitialize = initializeLayer(); // -// if(noErrorsOnInitialize) { +// if (noErrorsOnInitialize) { // mcMMO.p.getLogger().info("Successfully Loaded Compatibility Layer! (Player Attack Cooldown Exploit Prevention)"); // } // } else { diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java index c4617bd69..d114ea026 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarManager.java @@ -28,8 +28,7 @@ public class ExperienceBarManager { private HashSet alwaysVisible; private HashSet disabledBars; - public ExperienceBarManager(McMMOPlayer mcMMOPlayer) - { + public ExperienceBarManager(McMMOPlayer mcMMOPlayer) { this.mcMMOPlayer = mcMMOPlayer; init(); } @@ -44,15 +43,14 @@ public class ExperienceBarManager { disabledBars = new HashSet<>(); } - public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) - { - if(disabledBars.contains(primarySkillType) + public void updateExperienceBar(PrimarySkillType primarySkillType, Plugin plugin) { + if (disabledBars.contains(primarySkillType) || !ExperienceConfig.getInstance().isExperienceBarsEnabled() || !ExperienceConfig.getInstance().isExperienceBarEnabled(primarySkillType)) return; //Init Bar - if(experienceBars.get(primarySkillType) == null) + if (experienceBars.get(primarySkillType) == null) experienceBars.put(primarySkillType, new ExperienceBarWrapper(primarySkillType, mcMMOPlayer)); //Get Bar @@ -65,8 +63,7 @@ public class ExperienceBarManager { experienceBarWrapper.showExperienceBar(); //Setup Hide Bar Task - if(experienceBarHideTaskHashMap.get(primarySkillType) != null) - { + if (experienceBarHideTaskHashMap.get(primarySkillType) != null) { experienceBarHideTaskHashMap.get(primarySkillType).cancel(); } @@ -74,7 +71,7 @@ public class ExperienceBarManager { } private void scheduleHideTask(PrimarySkillType primarySkillType, Plugin plugin) { - if(alwaysVisible.contains(primarySkillType)) + if (alwaysVisible.contains(primarySkillType)) return; ExperienceBarHideTask experienceBarHideTask = new ExperienceBarHideTask(this, mcMMOPlayer, primarySkillType); @@ -82,14 +79,12 @@ public class ExperienceBarManager { experienceBarHideTaskHashMap.put(primarySkillType, experienceBarHideTask); } - public void hideExperienceBar(PrimarySkillType primarySkillType) - { - if(experienceBars.containsKey(primarySkillType)) + public void hideExperienceBar(PrimarySkillType primarySkillType) { + if (experienceBars.containsKey(primarySkillType)) experienceBars.get(primarySkillType).hideExperienceBar(); } - public void clearTask(PrimarySkillType primarySkillType) - { + public void clearTask(PrimarySkillType primarySkillType) { experienceBarHideTaskHashMap.remove(primarySkillType); } @@ -108,7 +103,7 @@ public class ExperienceBarManager { alwaysVisible.add(skillType); //Remove lingering tasks - if(experienceBarHideTaskHashMap.containsKey(skillType)) { + if (experienceBarHideTaskHashMap.containsKey(skillType)) { experienceBarHideTaskHashMap.get(skillType).cancel(); } @@ -119,7 +114,7 @@ public class ExperienceBarManager { disabledBars.add(skillType); //Remove lingering tasks - if(experienceBarHideTaskHashMap.containsKey(skillType)) { + if (experienceBarHideTaskHashMap.containsKey(skillType)) { experienceBarHideTaskHashMap.get(skillType).cancel(); } @@ -149,7 +144,7 @@ public class ExperienceBarManager { private void informPlayer(@NotNull ExperienceBarManager.@NotNull XPBarSettingTarget settingTarget, @Nullable PrimarySkillType primarySkillType) { //Inform player of setting change - if(settingTarget != XPBarSettingTarget.RESET) { + if (settingTarget != XPBarSettingTarget.RESET) { NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.SettingChanged", mcMMO.p.getSkillTools().getLocalizedSkillName(primarySkillType), settingTarget.toString()); } else { NotificationManager.sendPlayerInformationChatOnlyPrefixed(mcMMOPlayer.getPlayer(), "Commands.XPBar.Reset"); diff --git a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java index 185026ed9..d90eae7b2 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/experience/ExperienceBarWrapper.java @@ -29,8 +29,7 @@ public class ExperienceBarWrapper { protected String niceSkillName; protected String title; - public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) - { + public ExperienceBarWrapper(PrimarySkillType primarySkillType, McMMOPlayer mcMMOPlayer) { this.mcMMOPlayer = mcMMOPlayer; this.primarySkillType = primarySkillType; title = ""; @@ -43,8 +42,7 @@ public class ExperienceBarWrapper { initBar(); } - private void initBar() - { + private void initBar() { title = getTitleTemplate(); createBossBar(); } @@ -57,9 +55,9 @@ public class ExperienceBarWrapper { private String getTitleTemplate() { //If they are using extra details - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { return LocaleLoader.getString("XPBar.Template.EarlyGameBoost"); - } else if(ExperienceConfig.getInstance().getAddExtraDetails()) + } else if (ExperienceConfig.getInstance().getAddExtraDetails()) return LocaleLoader.getString("XPBar.Complex.Template", LocaleLoader.getString("XPBar."+niceSkillName, getLevel()), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); return LocaleLoader.getString("XPBar."+niceSkillName, getLevel(), getCurrentXP(), getMaxXP(), getPowerLevel(), getPercentageOfLevel()); @@ -99,24 +97,23 @@ public class ExperienceBarWrapper { public void setProgress(double v) { //Clamp Values - if(v < 0) + if (v < 0) bossBar.setProgress(0.0D); - else if(v > 1) + else if (v > 1) bossBar.setProgress(1.0D); else bossBar.setProgress(v); //Check player level - if(ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { + if (ExperienceConfig.getInstance().isEarlyGameBoostEnabled() && PlayerLevelUtils.qualifiesForEarlyGameBoost(mcMMOPlayer, primarySkillType)) { setColor(BarColor.YELLOW); } else { setColor(ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType)); } //Every time progress updates we need to check for a title update - if(getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) - { + if (getLevel() != lastLevelUpdated || ExperienceConfig.getInstance().getDoExperienceBarsAlwaysUpdateTitle()) { updateTitle(); lastLevelUpdated = getLevel(); } @@ -134,23 +131,19 @@ public class ExperienceBarWrapper { return bossBar.isVisible(); } - public void hideExperienceBar() - { + public void hideExperienceBar() { bossBar.setVisible(false); } - public void showExperienceBar() - { + public void showExperienceBar() { bossBar.setVisible(true); } - /*public NamespacedKey getKey() - { + /*public NamespacedKey getKey() { return bossBar }*/ - private void createBossBar() - { + private void createBossBar() { bossBar = mcMMOPlayer.getPlayer().getServer().createBossBar( title, ExperienceConfig.getInstance().getExperienceBarColor(primarySkillType), diff --git a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java index 6685e816b..01964d0a8 100644 --- a/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java +++ b/src/main/java/com/gmail/nossr50/util/experience/FormulaManager.java @@ -135,8 +135,7 @@ public class FormulaManager { * @param formulaType target formulaType */ private int processXPToNextLevel(int level, FormulaType formulaType) { - if(mcMMO.isRetroModeEnabled()) - { + if (mcMMO.isRetroModeEnabled()) { return processXPRetroToNextLevel(level, formulaType); } else { return processStandardXPToNextLevel(level, formulaType); @@ -151,7 +150,7 @@ public class FormulaManager { private int processStandardXPToNextLevel(int level, FormulaType formulaType) { Map experienceMapRef = formulaType == FormulaType.LINEAR ? experienceNeededStandardLinear : experienceNeededStandardExponential; - if(!experienceMapRef.containsKey(level)) { + if (!experienceMapRef.containsKey(level)) { int experienceSum = 0; int retroIndex = (level * 10) + 1; diff --git a/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java b/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java index 47f41a82e..ea114508e 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java +++ b/src/main/java/com/gmail/nossr50/util/platform/MajorMinorPatchVersion.java @@ -73,7 +73,7 @@ public abstract class MajorMinorPatchVersion implements Versioned { @Override public String getVersionStr() { - if(isPatch()) { + if (isPatch()) { return majorVersion.getVersionString() + "." + minorVersion + "." + patchVersion; diff --git a/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java b/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java index 387d831d1..34ccdede9 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java +++ b/src/main/java/com/gmail/nossr50/util/platform/MinecraftGameVersion.java @@ -38,21 +38,21 @@ public class MinecraftGameVersion extends MajorMinorPatchVersion { public boolean isAtLeast(int majorVerNumber, int minorVerNumber, int patchVerNumber) { //First check if the major version is higher, if it is we have no need to check minor version or patch version - if(getMajorVersion().asInt() > majorVerNumber) { + if (getMajorVersion().asInt() > majorVerNumber) { return true; //Major version is one higher and hierarchically more important than the other versions } - if(getMajorVersion().asInt() < majorVerNumber) { + if (getMajorVersion().asInt() < majorVerNumber) { return false; //Major version is below, so return false } //Major version meets the requirement, check minor version - if(getMinorVersion().asInt() > minorVerNumber) { + if (getMinorVersion().asInt() > minorVerNumber) { return true; //Minor version is one higher and hierarchically more important than patch version, so exit here } - if(getMinorVersion().asInt() < minorVerNumber) { + if (getMinorVersion().asInt() < minorVerNumber) { return false; //Minor version is at least one version behind, return false } diff --git a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java index e68ff1912..721df8091 100644 --- a/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java +++ b/src/main/java/com/gmail/nossr50/util/platform/PlatformManager.java @@ -72,23 +72,20 @@ public class PlatformManager { //TODO: Rewrite this properly once we actually support a not-bukkit platform private @NotNull ServerSoftwareType determinePlatformType() { - if(Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper")) + if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("paper")) return ServerSoftwareType.PAPER; - else if(Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("spigot")) + else if (Bukkit.getVersion().toLowerCase(Locale.ENGLISH).contains("spigot")) return ServerSoftwareType.SPIGOT; else return ServerSoftwareType.CRAFT_BUKKIT; } - public ServerSoftwareType getServerSoftware() - { + public ServerSoftwareType getServerSoftware() { return platform.getServerSoftwareType(); } - public String getServerSoftwareStr() - { - switch(getServerSoftware()) - { + public String getServerSoftwareStr() { + switch(getServerSoftware()) { case PAPER: return "Paper"; case SPIGOT: diff --git a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java index 615ae3fbb..4750c5c48 100644 --- a/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/NotificationManager.java @@ -43,9 +43,8 @@ public class NotificationManager { * @param notificationType notifications defined type * @param key the locale key for the notifications defined message */ - public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) - { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + public static void sendPlayerInformation(Player player, NotificationType notificationType, String key) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; McMMOMessageType destination @@ -59,9 +58,8 @@ public class NotificationManager { } - public static boolean doesPlayerUseNotifications(Player player) - { - if(UserManager.getPlayer(player) == null) + public static boolean doesPlayerUseNotifications(Player player) { + if (UserManager.getPlayer(player) == null) return false; else return UserManager.getPlayer(player).useChatNotifications(); @@ -77,23 +75,20 @@ public class NotificationManager { * @param values values to be injected into the locale string */ public static void sendNearbyPlayersInformation(Player targetPlayer, NotificationType notificationType, String key, - String... values) - { + String... values) { sendPlayerInformation(targetPlayer, notificationType, key, values); } - public static void sendPlayerInformationChatOnly(Player player, String key, String... values) - { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + public static void sendPlayerInformationChatOnly(Player player, String key, String... values) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; String preColoredString = LocaleLoader.getString(key, (Object[]) values); player.sendMessage(preColoredString); } - public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, String... values) - { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + public static void sendPlayerInformationChatOnlyPrefixed(Player player, String key, String... values) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; String preColoredString = LocaleLoader.getString(key, (Object[]) values); @@ -102,9 +97,8 @@ public class NotificationManager { } public static void sendPlayerInformation(Player player, NotificationType notificationType, String key, - String... values) - { - if(UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) + String... values) { + if (UserManager.getPlayer(player) == null || !UserManager.getPlayer(player).useChatNotifications()) return; McMMOMessageType destination = mcMMO.p.getAdvancedConfig().doesNotificationUseActionBar(notificationType) ? McMMOMessageType.ACTION_BAR : McMMOMessageType.SYSTEM; @@ -121,14 +115,13 @@ public class NotificationManager { final Audience audience = mcMMO.getAudiences().player(player); - //If the message is being sent to the action bar we need to check if the copy if a copy is sent to the chat system + Component notificationTextComponent = customEvent.getNotificationTextComponent(); - if(customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) - { + if (customEvent.getChatMessageType() == McMMOMessageType.ACTION_BAR) { audience.sendActionBar(notificationTextComponent); - if(customEvent.isMessageAlsoBeingSentToChat()) - { + // If the message is being sent to the action bar we need to check if a copy is also sent to the chat system + if (customEvent.isMessageAlsoBeingSentToChat()) { //Send copy to chat system audience.sendMessage(notificationTextComponent); } @@ -157,9 +150,8 @@ public class NotificationManager { * @param newLevel new level of that skill */ public static void sendPlayerLevelUpNotification(McMMOPlayer mcMMOPlayer, PrimarySkillType skillName, - int levelsGained, int newLevel) - { - if(!mcMMOPlayer.useChatNotifications()) + int levelsGained, int newLevel) { + if (!mcMMOPlayer.useChatNotifications()) return; McMMOMessageType destination @@ -177,17 +169,14 @@ public class NotificationManager { sendNotification(mcMMOPlayer.getPlayer(), customEvent); } - public static void broadcastTitle(Server server, String title, String subtitle, int i1, int i2, int i3) - { - for(Player player : server.getOnlinePlayers()) - { + public static void broadcastTitle(Server server, String title, String subtitle, int i1, int i2, int i3) { + for(Player player : server.getOnlinePlayers()) { player.sendTitle(title, subtitle, i1, i2, i3); } } - public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) - { - if(!mcMMOPlayer.useChatNotifications()) + public static void sendPlayerUnlockNotification(McMMOPlayer mcMMOPlayer, SubSkillType subSkillType) { + if (!mcMMOPlayer.useChatNotifications()) return; //CHAT MESSAGE @@ -206,13 +195,11 @@ public class NotificationManager { */ private static void sendAdminNotification(String msg) { //If its not enabled exit - if(!mcMMO.p.getGeneralConfig().adminNotifications()) + if (!mcMMO.p.getGeneralConfig().adminNotifications()) return; - for(Player player : Bukkit.getServer().getOnlinePlayers()) - { - if(player.isOp() || Permissions.adminChat(player)) - { + for(Player player : Bukkit.getServer().getOnlinePlayers()) { + if (player.isOp() || Permissions.adminChat(player)) { player.sendMessage(LocaleLoader.getString("Notifications.Admin.Format.Others", msg)); } } @@ -242,15 +229,13 @@ public class NotificationManager { */ String senderName = LocaleLoader.getString("Server.ConsoleName"); - if(commandSender instanceof Player) - { + if (commandSender instanceof Player) { senderName = ((Player) commandSender).getDisplayName() + ChatColor.RESET + "-" + ((Player) commandSender).getUniqueId(); } //Send the notification - switch(sensitiveCommandType) - { + switch(sensitiveCommandType) { case XPRATE_MODIFY: sendAdminNotification(LocaleLoader.getString("Notifications.Admin.XPRate.Start.Others", addItemToFirstPositionOfArray(senderName, args))); @@ -285,20 +270,20 @@ public class NotificationManager { } public static void processLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, @NotNull PrimarySkillType primarySkillType, int level) { - if(level <= 0) + if (level <= 0) return; //Check if broadcasting is enabled - if(mcMMO.p.getGeneralConfig().shouldLevelUpBroadcasts()) { + if (mcMMO.p.getGeneralConfig().shouldLevelUpBroadcasts()) { //Permission check - if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { + if (!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { return; } int levelInterval = mcMMO.p.getGeneralConfig().getLevelUpBroadcastInterval(); int remainder = level % levelInterval; - if(remainder == 0) { + if (remainder == 0) { //Grab appropriate audience Audience audience = mcMMO.getAudiences().filter(getLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); //TODO: Make prettier @@ -329,20 +314,20 @@ public class NotificationManager { //TODO: Remove the code duplication, am lazy atm //TODO: Fix broadcasts being skipped for situations where a player skips over the milestone like with the addlevels command public static void processPowerLevelUpBroadcasting(@NotNull McMMOPlayer mmoPlayer, int powerLevel) { - if(powerLevel <= 0) + if (powerLevel <= 0) return; //Check if broadcasting is enabled - if(mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcasts()) { + if (mcMMO.p.getGeneralConfig().shouldPowerLevelUpBroadcasts()) { //Permission check - if(!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { + if (!Permissions.levelUpBroadcast(mmoPlayer.getPlayer())) { return; } int levelInterval = mcMMO.p.getGeneralConfig().getPowerLevelUpBroadcastInterval(); int remainder = powerLevel % levelInterval; - if(remainder == 0) { + if (remainder == 0) { //Grab appropriate audience Audience audience = mcMMO.getAudiences().filter(getPowerLevelUpBroadcastPredicate(mmoPlayer.getPlayer())); //TODO: Make prettier diff --git a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java index 1f0cba2f1..5a0d5f3de 100644 --- a/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java +++ b/src/main/java/com/gmail/nossr50/util/player/PlayerLevelUtils.java @@ -19,7 +19,7 @@ public class PlayerLevelUtils { // int levelCap = Config.getInstance().getLevelCap(primarySkillType); // int cap; // -// if(levelCap == Integer.MAX_VALUE || levelCap <= 0) +// if (levelCap == Integer.MAX_VALUE || levelCap <= 0) // { // cap = Config.getInstance().getIsRetroMode() ? 50 : 5; // } else { @@ -30,8 +30,7 @@ public class PlayerLevelUtils { // } // } - public int getEarlyGameCutoff(PrimarySkillType primarySkillType) - { + public int getEarlyGameCutoff(PrimarySkillType primarySkillType) { return 1; } diff --git a/src/main/java/com/gmail/nossr50/util/player/UserManager.java b/src/main/java/com/gmail/nossr50/util/player/UserManager.java index a7f4a840b..04457d103 100644 --- a/src/main/java/com/gmail/nossr50/util/player/UserManager.java +++ b/src/main/java/com/gmail/nossr50/util/player/UserManager.java @@ -30,14 +30,14 @@ public final class UserManager { public static void track(@NotNull McMMOPlayer mcMMOPlayer) { mcMMOPlayer.getPlayer().setMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, new FixedMetadataValue(mcMMO.p, mcMMOPlayer)); - if(playerDataSet == null) + if (playerDataSet == null) playerDataSet = new HashSet<>(); playerDataSet.add(mcMMOPlayer); //for sync saves on shutdown } public static void cleanupPlayer(McMMOPlayer mcMMOPlayer) { - if(playerDataSet != null) + if (playerDataSet != null) playerDataSet.remove(mcMMOPlayer); } @@ -49,13 +49,13 @@ public final class UserManager { public static void remove(@NotNull Player player) { McMMOPlayer mcMMOPlayer = getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; mcMMOPlayer.cleanup(); player.removeMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA, mcMMO.p); - if(playerDataSet != null) { + if (playerDataSet != null) { playerDataSet.remove(mcMMOPlayer); //Clear sync save tracking } } @@ -68,7 +68,7 @@ public final class UserManager { remove(player); } - if(playerDataSet != null) + if (playerDataSet != null) playerDataSet.clear(); //Clear sync save tracking } @@ -76,7 +76,7 @@ public final class UserManager { * Save all users ON THIS THREAD. */ public static void saveAll() { - if(playerDataSet == null) + if (playerDataSet == null) return; ImmutableList trackedSyncData = ImmutableList.copyOf(playerDataSet); @@ -84,13 +84,11 @@ public final class UserManager { mcMMO.p.getLogger().info("Saving mcMMOPlayers... (" + trackedSyncData.size() + ")"); for (McMMOPlayer playerData : trackedSyncData) { - try - { + try { LogUtils.debug(mcMMO.p.getLogger(), "Saving data for player: "+playerData.getPlayerName()); playerData.getProfile().save(true); } - catch (Exception e) - { + catch (Exception e) { mcMMO.p.getLogger().warning("Could not save mcMMO player data for player: " + playerData.getPlayerName()); } } @@ -139,14 +137,14 @@ public final class UserManager { */ public static @Nullable McMMOPlayer getPlayer(@Nullable Player player) { //Avoid Array Index out of bounds - if(player != null && player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) + if (player != null && player.hasMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA)) return (McMMOPlayer) player.getMetadata(MetadataConstants.METADATA_KEY_PLAYER_DATA).get(0).value(); else return null; } private static @Nullable McMMOPlayer retrieveMcMMOPlayer(@Nullable String playerName, boolean offlineValid) { - if(playerName == null) + if (playerName == null) return null; Player player = mcMMO.p.getServer().getPlayerExact(playerName); diff --git a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java index 4836efedc..ca4a67de8 100644 --- a/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java +++ b/src/main/java/com/gmail/nossr50/util/random/ProbabilityUtil.java @@ -11,49 +11,68 @@ import com.gmail.nossr50.util.player.UserManager; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.VisibleForTesting; import java.text.DecimalFormat; +import static java.util.Objects.requireNonNull; + public class ProbabilityUtil { public static final @NotNull DecimalFormat percent = new DecimalFormat("##0.00%"); public static final double LUCKY_MODIFIER = 1.333D; /** - * Return a chance of success in "percentage" format, show to the player in UI elements + * Return a chance of success in "percentage" format, shown to the player in UI elements * * @param player target player * @param subSkillType target subskill * @param isLucky whether to apply luck modifiers * * @return "percentage" representation of success + * @deprecated use {@link #chanceOfSuccessPercentage(McMMOPlayer, SubSkillType, boolean)} instead */ - public static double chanceOfSuccessPercentage(@NotNull Player player, + @Deprecated(forRemoval = true, since = "2.2.010") + public static double chanceOfSuccessPercentage(@Nullable Player player, @NotNull SubSkillType subSkillType, boolean isLucky) { - Probability probability = getSubSkillProbability(subSkillType, player); + return chanceOfSuccessPercentage(requireNonNull(UserManager.getPlayer(player)), subSkillType, isLucky); + } + + public static double chanceOfSuccessPercentage(@Nullable McMMOPlayer mmoPlayer, + @NotNull SubSkillType subSkillType, + boolean isLucky) { + Probability probability = getSubSkillProbability(subSkillType, mmoPlayer); //Probability values are on a 0-1 scale and need to be "transformed" into a 1-100 scale double percentageValue = probability.getValue(); //Doesn't need to be scaled //Apply lucky modifier - if(isLucky) { + if (isLucky) { percentageValue *= LUCKY_MODIFIER; } return percentageValue; } + /** + * Return a chance of success as a double representing a "percentage". + * + * @param probability the probability of success + * @param isLucky whether to apply luck modifiers + * @return a double as a "percentage" representation of success + */ public static double chanceOfSuccessPercentage(@NotNull Probability probability, boolean isLucky) { //Probability values are on a 0-1 scale and need to be "transformed" into a 1-100 scale double percentageValue = probability.getValue(); //Apply lucky modifier - if(isLucky) { + if (isLucky) { percentageValue *= LUCKY_MODIFIER; } return percentageValue; } + @VisibleForTesting static Probability getStaticRandomChance(@NotNull SubSkillType subSkillType) throws InvalidStaticChance { return switch (subSkillType) { case AXES_ARMOR_IMPACT -> Probability.ofPercent(mcMMO.p.getAdvancedConfig().getImpactChance()); @@ -66,7 +85,7 @@ public class ProbabilityUtil { static SkillProbabilityType getProbabilityType(@NotNull SubSkillType subSkillType) { SkillProbabilityType skillProbabilityType = SkillProbabilityType.DYNAMIC_CONFIGURABLE; - if(subSkillType == SubSkillType.TAMING_FAST_FOOD_SERVICE + if (subSkillType == SubSkillType.TAMING_FAST_FOOD_SERVICE || subSkillType == SubSkillType.AXES_ARMOR_IMPACT || subSkillType == SubSkillType.AXES_GREATER_IMPACT) skillProbabilityType = SkillProbabilityType.STATIC_CONFIGURABLE; @@ -74,19 +93,20 @@ public class ProbabilityUtil { return skillProbabilityType; } - static @NotNull Probability ofSubSkill(@Nullable Player player, - @NotNull SubSkillType subSkillType) { + @Deprecated(forRemoval = true, since = "2.2.010") + private static @NotNull Probability ofSubSkill(@Nullable Player player, @NotNull SubSkillType subSkillType) { + // no null check needed here + return ofSubSkill(UserManager.getPlayer(player), subSkillType); + } + + private static @NotNull Probability ofSubSkill(@Nullable McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkillType) { switch (getProbabilityType(subSkillType)) { case DYNAMIC_CONFIGURABLE: double probabilityCeiling; double skillLevel; double maxBonusLevel; // If a skill level is equal to the cap, it has the full probability - if (player != null) { - McMMOPlayer mmoPlayer = UserManager.getPlayer(player); - if (mmoPlayer == null) { - return Probability.ofPercent(0); - } + if (mmoPlayer != null) { skillLevel = mmoPlayer.getSkillLevel(subSkillType.getParentSkill()); } else { skillLevel = 0; @@ -101,10 +121,10 @@ public class ProbabilityUtil { try { return getStaticRandomChance(subSkillType); } catch (InvalidStaticChance invalidStaticChance) { - invalidStaticChance.printStackTrace(); + throw new RuntimeException(invalidStaticChance); } default: - throw new RuntimeException("No case in switch statement for Skill Probability Type!"); + throw new IllegalStateException("No case in switch statement for Skill Probability Type!"); } } @@ -123,16 +143,45 @@ public class ProbabilityUtil { * The outcome of the probability can also be modified by this event that is called * * @param subSkillType target subskill - * @param player target player, can be null (null players are given odds equivalent to a player with no levels or luck) + * @param player target player + * can be null (null players are given odds equivalent to a player with no levels or luck) + * @return true if the Skill RNG succeeds, false if it fails + * @deprecated use {@link #isSkillRNGSuccessful(SubSkillType, McMMOPlayer)} instead + */ + @Deprecated(forRemoval = true, since = "2.2.010") + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable Player player) { + return isSkillRNGSuccessful(subSkillType, UserManager.getPlayer(player)); + } + + /** + * This is one of several Skill RNG check methods + * This helper method is for specific {@link SubSkillType}, + * which help mcMMO understand where the RNG values used in our calculations come from this {@link SubSkillType} + *

+ * 1) Determine where the RNG values come from for the passed {@link SubSkillType} + * NOTE: In the config file, there are values which are static and which are more dynamic, + * this is currently a bit hardcoded and will need to be updated manually + *

+ * 2) Determine whether to use Lucky multiplier and influence the outcome + *

+ * 3) + * Creates a {@link Probability} and pipes it to {@link ProbabilityUtil} which processes the result and returns it + *

+ * This also calls a {@link SubSkillEvent} which can be cancelled, if it is cancelled this will return false + * The outcome of the probability can also be modified by this event that is called + * + * @param subSkillType target subskill + * @param mmoPlayer target player + * can be null (null players are given odds equivalent to a player with no levels or luck) * @return true if the Skill RNG succeeds, false if it fails */ - public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) { - final Probability probability = getSkillProbability(subSkillType, player); + public static boolean isSkillRNGSuccessful(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer) { + final Probability probability = getSkillProbability(subSkillType, mmoPlayer); //Luck - boolean isLucky = Permissions.lucky(player, subSkillType.getParentSkill()); + boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), subSkillType.getParentSkill()); - if(isLucky) { + if (isLucky) { return probability.evaluate(LUCKY_MODIFIER); } else { return probability.evaluate(); @@ -143,29 +192,50 @@ public class ProbabilityUtil { * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}. * This does not take into account perks such as lucky for the player. * This is affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate it. + * Null players will be treated as zero skill players. * * @param subSkillType the target subskill * @param player the target player + * can be null (null players have the worst odds) + * @return the probability for this skill + * @deprecated use {@link #getSkillProbability(SubSkillType, McMMOPlayer)} instead + */ + @Deprecated(forRemoval = true) + public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @Nullable Player player) { + return getSkillProbability(subSkillType, UserManager.getPlayer(player)); + } + + /** + * Returns the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player}. + * This does not take into account perks such as lucky for the player. + * This is affected by other plugins who can listen to the {@link SubSkillEvent} and cancel it or mutate it. + * Null players will be treated as zero skill players. + * + * @param subSkillType the target subskill + * @param mmoPlayer the target player + * can be null (null players have the worst odds) * @return the probability for this skill */ - public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @NotNull Player player) { - //Process probability - Probability probability = getSubSkillProbability(subSkillType, player); + public static Probability getSkillProbability(@NotNull SubSkillType subSkillType, @Nullable McMMOPlayer mmoPlayer) { + // Process probability + Probability probability = getSubSkillProbability(subSkillType, mmoPlayer); - //Send out event - SubSkillEvent subSkillEvent = EventUtils.callSubSkillEvent(player, subSkillType); + // Send out event + if (mmoPlayer != null) { + SubSkillEvent subSkillEvent = EventUtils.callSubSkillEvent(mmoPlayer, subSkillType); - if(subSkillEvent.isCancelled()) { - return Probability.ALWAYS_FAILS; + if (subSkillEvent.isCancelled()) { + return Probability.ALWAYS_FAILS; + } + + // Result modifier + double resultModifier = subSkillEvent.getResultModifier(); + + // Mutate probability + if (resultModifier != 1.0D) + probability = Probability.ofPercent(probability.getValue() * resultModifier); } - //Result modifier - double resultModifier = subSkillEvent.getResultModifier(); - - //Mutate probability - if(resultModifier != 1.0D) - probability = Probability.ofPercent(probability.getValue() * resultModifier); - return probability; } @@ -177,12 +247,11 @@ public class ProbabilityUtil { * @param player the target player can be null (null players have the worst odds) * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive) * @return true if the RNG succeeds, false if it fails + * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, double)} instead */ + @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, double probabilityPercentage) { - //Grab a probability converted from a "percentage" value - Probability probability = Probability.ofPercent(probabilityPercentage); - - return isStaticSkillRNGSuccessful(primarySkillType, player, probability); + return isStaticSkillRNGSuccessful(primarySkillType, player, Probability.ofPercent(probabilityPercentage)); } /** @@ -190,14 +259,51 @@ public class ProbabilityUtil { * This helper method is specific to static value RNG, which can be influenced by a player's Luck * * @param primarySkillType the related primary skill - * @param player the target player, can be null (null players have the worst odds) - * @param probability the probability of this player succeeding + * @param mmoPlayer the target player can be null (null players have the worst odds) + * @param probabilityPercentage the probability of this player succeeding in "percentage" format (0-100 inclusive) * @return true if the RNG succeeds, false if it fails */ - public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, @Nullable Player player, @NotNull Probability probability) { - boolean isLucky = player != null && Permissions.lucky(player, primarySkillType); + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable McMMOPlayer mmoPlayer, double probabilityPercentage) { + //Grab a probability converted from a "percentage" value + final Probability probability = Probability.ofPercent(probabilityPercentage); - if(isLucky) { + return isStaticSkillRNGSuccessful(primarySkillType, mmoPlayer, probability); + } + + /** + * This is one of several Skill RNG check methods + * This helper method is specific to static value RNG, which can be influenced by a player's Luck + * + * @param primarySkillType the related primary skill + * @param player the target player + * can be null (null players have the worst odds) + * @param probability the probability of this player succeeding + * @return true if the RNG succeeds, false if it fails + * @deprecated use {@link #isStaticSkillRNGSuccessful(PrimarySkillType, McMMOPlayer, Probability)} instead, this + * method is redundant and will be removed. + */ + @Deprecated(forRemoval = true, since = "2.2.010") + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable Player player, @NotNull Probability probability) { + return isStaticSkillRNGSuccessful(primarySkillType, UserManager.getPlayer(player), probability); + } + + /** + * This is one of several Skill RNG check methods + * This helper method is specific to static value RNG, which can be influenced by a mmoPlayer's Luck + * + * @param primarySkillType the related primary skill + * @param mmoPlayer the target mmoPlayer + * can be null (null players have the worst odds) + * @param probability the probability of this mmoPlayer succeeding + * @return true if the RNG succeeds, false if it fails + */ + public static boolean isStaticSkillRNGSuccessful(@NotNull PrimarySkillType primarySkillType, + @Nullable McMMOPlayer mmoPlayer, @NotNull Probability probability) { + boolean isLucky = mmoPlayer != null && Permissions.lucky(mmoPlayer.getPlayer(), primarySkillType); + + if (isLucky) { return probability.evaluate(LUCKY_MODIFIER); } else { return probability.evaluate(); @@ -209,25 +315,57 @@ public class ProbabilityUtil { * @param subSkillType target subskill * @param player target player * @return true if the skill succeeds (wasn't cancelled by any other plugin) + * @deprecated use {@link #isNonRNGSkillActivationSuccessful(SubSkillType, McMMOPlayer)} instead */ + @Deprecated(forRemoval = true, since = "2.2.010") public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, @NotNull Player player) { - return !EventUtils.callSubSkillEvent(player, subSkillType).isCancelled(); + return isNonRNGSkillActivationSuccessful(subSkillType, requireNonNull(UserManager.getPlayer(player))); } /** - * Grab the {@link Probability} for a specific {@link SubSkillType} for a specific {@link Player} - * + * Skills activate without RNG, this allows other plugins to prevent that activation * @param subSkillType target subskill - * @param player target player - * @return the Probability of this skill succeeding + * @param mmoPlayer target player + * @return true if the skill succeeds (wasn't cancelled by any other plugin) */ - public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, @Nullable Player player) { + public static boolean isNonRNGSkillActivationSuccessful(@NotNull SubSkillType subSkillType, + @NotNull McMMOPlayer mmoPlayer) { + return !EventUtils.callSubSkillEvent(mmoPlayer, subSkillType).isCancelled(); + } + + /** + * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given {@link Player}. + * + * @param subSkillType The targeted subskill. + * @param player The player in question. + * If null, the method treats it as a player with no levels or luck and calculates the probability + * accordingly. + * @return The probability that the specified skill will succeed. + * @deprecated use {@link #getSubSkillProbability(SubSkillType, McMMOPlayer)} instead + */ + @Deprecated(forRemoval = true, since = "2.2.010") + public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, + @Nullable Player player) { return ProbabilityUtil.ofSubSkill(player, subSkillType); } - public static @NotNull String[] getRNGDisplayValues(@NotNull Player player, @NotNull SubSkillType subSkill) { - double firstValue = chanceOfSuccessPercentage(player, subSkill, false); - double secondValue = chanceOfSuccessPercentage(player, subSkill, true); + /** + * Retrieves the {@link Probability} of success for a specified {@link SubSkillType} for a given {@link Player}. + * + * @param subSkillType The targeted subskill. + * @param mmoPlayer The player in question. + * If null, the method treats it as a player with no levels or luck and calculates the probability + * accordingly. + * @return The probability that the specified skill will succeed. + */ + public static @NotNull Probability getSubSkillProbability(@NotNull SubSkillType subSkillType, + @Nullable McMMOPlayer mmoPlayer) { + return ProbabilityUtil.ofSubSkill(mmoPlayer, subSkillType); + } + + public static @NotNull String[] getRNGDisplayValues(@Nullable McMMOPlayer mmoPlayer, @NotNull SubSkillType subSkill) { + double firstValue = chanceOfSuccessPercentage(mmoPlayer, subSkill, false); + double secondValue = chanceOfSuccessPercentage(mmoPlayer, subSkill, true); return new String[]{percent.format(firstValue), percent.format(secondValue)}; } diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java index 331d3f5b3..7bb64188d 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardManager.java @@ -155,8 +155,7 @@ public class ScoreboardManager { private static String formatAbility(ChatColor color, String abilityName) { if (mcMMO.p.getGeneralConfig().getShowAbilityNames()) { return getShortenedName(color + abilityName); - } - else { + } else { return color + LocaleLoader.getString("Scoreboard.Misc.Ability"); } } @@ -185,18 +184,18 @@ public class ScoreboardManager { // Called by PlayerQuitEvent listener and OnPlayerTeleport under certain circumstances public static void teardownPlayer(Player player) { - if(player == null) + if (player == null) return; //Hacky world blacklist fix - if(player.isOnline() && player.isValid()) { - if(Bukkit.getServer().getScoreboardManager() != null) + if (player.isOnline() && player.isValid()) { + if (Bukkit.getServer().getScoreboardManager() != null) player.setScoreboard(Bukkit.getServer().getScoreboardManager().getMainScoreboard()); } - if(getWrapper(player) != null) { + if (getWrapper(player) != null) { ScoreboardWrapper wrapper = PLAYER_SCOREBOARDS.remove(player.getName()); - if(wrapper.revertTask != null) { + if (wrapper.revertTask != null) { wrapper.revertTask.cancel(); } } @@ -225,12 +224,12 @@ public class ScoreboardManager { // Selfboards ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { if ((wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) || (wrapper.isStatsScoreboard()) && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } @@ -270,12 +269,12 @@ public class ScoreboardManager { // Selfboards ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { if ((wrapper.isCooldownScoreboard() || wrapper.isSkillScoreboard() && wrapper.targetSkill == skill) && wrapper.isBoardShown()) { wrapper.doSidebarUpdateSoon(); } @@ -290,12 +289,12 @@ public class ScoreboardManager { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeSkill(skill); @@ -309,12 +308,12 @@ public class ScoreboardManager { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeSkill(primarySkillType); @@ -328,7 +327,7 @@ public class ScoreboardManager { // Do NOT run if already shown if (wrapper != null && wrapper.isBoardShown()) { - if(wrapper.isBoardShown()) + if (wrapper.isBoardShown()) return; wrapper.setOldScoreboard(); @@ -340,7 +339,7 @@ public class ScoreboardManager { public static void enablePlayerStatsScoreboard(Player player) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) + if (wrapper == null) return; @@ -353,12 +352,12 @@ public class ScoreboardManager { public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull PlayerProfile targetProfile) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeInspectStats(targetProfile); @@ -369,12 +368,12 @@ public class ScoreboardManager { public static void enablePlayerInspectScoreboard(@NotNull Player player, @NotNull McMMOPlayer targetMcMMOPlayer) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeInspectStats(targetMcMMOPlayer); @@ -385,12 +384,12 @@ public class ScoreboardManager { public static void enablePlayerCooldownScoreboard(Player player) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeCooldowns(); @@ -401,12 +400,12 @@ public class ScoreboardManager { public static void showPlayerRankScoreboard(Player player, Map rank) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeSelfRank(); wrapper.acceptRankData(rank); @@ -418,12 +417,12 @@ public class ScoreboardManager { public static void showPlayerRankScoreboardOthers(Player player, String targetName, Map rank) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeInspectRank(targetName); wrapper.acceptRankData(rank); @@ -436,12 +435,12 @@ public class ScoreboardManager { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeTop(skill, pageNumber); wrapper.acceptLeaderboardData(stats); @@ -453,12 +452,12 @@ public class ScoreboardManager { public static void showTopPowerScoreboard(Player player, int pageNumber, List stats) { ScoreboardWrapper wrapper = getWrapper(player); - if(wrapper == null) { + if (wrapper == null) { setupPlayer(player); wrapper = getWrapper(player); } - if(wrapper != null) { + if (wrapper != null) { wrapper.setOldScoreboard(); wrapper.setTypeTopPower(pageNumber); wrapper.acceptLeaderboardData(stats); @@ -468,7 +467,7 @@ public class ScoreboardManager { } public static @Nullable ScoreboardWrapper getWrapper(Player player) { - if(PLAYER_SCOREBOARDS.get(player.getName()) == null) { + if (PLAYER_SCOREBOARDS.get(player.getName()) == null) { makeNewScoreboard(player); } @@ -518,7 +517,7 @@ public class ScoreboardManager { */ public static @Nullable Objective getPowerLevelObjective() { if (!mcMMO.p.getGeneralConfig().getPowerLevelTagsEnabled()) { - if(getScoreboardManager() == null) + if (getScoreboardManager() == null) return null; Objective objective = getScoreboardManager().getMainScoreboard().getObjective(POWER_OBJECTIVE); @@ -532,7 +531,7 @@ public class ScoreboardManager { } - if(getScoreboardManager() == null) + if (getScoreboardManager() == null) return null; Objective powerObjective = getScoreboardManager().getMainScoreboard().getObjective(POWER_OBJECTIVE); @@ -553,8 +552,7 @@ public class ScoreboardManager { public static void changeScoreboard(ScoreboardWrapper wrapper, int displayTime) { if (displayTime == -1) { wrapper.showBoardWithNoRevert(); - } - else { + } else { wrapper.showBoardAndScheduleRevert(displayTime * Misc.TICK_CONVERSION_FACTOR); } } @@ -580,7 +578,7 @@ public class ScoreboardManager { } public static @Nullable ScoreboardWrapper makeNewScoreboard(Player player) { - if(getScoreboardManager() == null) + if (getScoreboardManager() == null) return null; //Call our custom event diff --git a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java index 4d2d51560..f9988fb21 100644 --- a/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java +++ b/src/main/java/com/gmail/nossr50/util/scoreboards/ScoreboardWrapper.java @@ -18,7 +18,6 @@ import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.scoreboards.ScoreboardManager.SidebarType; import com.gmail.nossr50.util.skills.SkillTools; import com.tcoded.folialib.wrapper.task.WrappedTask; -import org.apache.commons.lang.Validate; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; @@ -30,6 +29,8 @@ import org.jetbrains.annotations.NotNull; import java.util.List; import java.util.Map; +import static java.util.Objects.requireNonNull; + public class ScoreboardWrapper { public static final String SIDE_OBJECTIVE = "mcMMO_sideObjective"; public static final String POWER_OBJECTIVE = "mcMMO_powerObjective"; @@ -62,7 +63,7 @@ public class ScoreboardWrapper { private void initBoard() { sidebarType = SidebarType.NONE; - if(registered) { + if (registered) { //Make sure our references are pointed at the right things sidebarObjective = scoreboard.getObjective(ScoreboardManager.SIDEBAR_OBJECTIVE); powerObjective = scoreboard.getObjective(ScoreboardManager.POWER_OBJECTIVE); @@ -111,8 +112,7 @@ public class ScoreboardWrapper { // Stop updating if it's no longer something displaying cooldowns if (isBoardShown() && (isSkillScoreboard() || isCooldownScoreboard())) { doSidebarUpdateSoon(); - } - else { + } else { stopCooldownUpdating(); } } @@ -175,11 +175,10 @@ public class ScoreboardWrapper { if (previousBoard == scoreboard) { // Already displaying it if (this.oldBoard == null) { // (Shouldn't happen) Use failsafe value - we're already displaying our board, but we don't have the one we should revert to - if(mcMMO.p.getServer().getScoreboardManager() != null) + if (mcMMO.p.getServer().getScoreboardManager() != null) this.oldBoard = mcMMO.p.getServer().getScoreboardManager().getMainScoreboard(); } - } - else { + } else { this.oldBoard = previousBoard; } } @@ -218,7 +217,7 @@ public class ScoreboardWrapper { // TODO is there any way to do the time that looks acceptable? // player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Timer", StringUtils.capitalize(sidebarType.toString().toLowerCase(Locale.ENGLISH)), ticks / 20F)); - if(UserManager.getPlayer(playerName) == null) + if (UserManager.getPlayer(playerName) == null) return; PlayerProfile profile = UserManager.getPlayer(player).getProfile(); @@ -230,8 +229,7 @@ public class ScoreboardWrapper { if (!tippedKeep) { tippedKeep = true; player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Tip.Keep")); - } - else if (!tippedClear) { + } else if (!tippedClear) { tippedClear = true; player.sendMessage(LocaleLoader.getString("Commands.Scoreboard.Tip.Clear")); profile.increaseTipsShown(); @@ -256,8 +254,7 @@ public class ScoreboardWrapper { //Modify the player based on the event event.getTargetPlayer().setScoreboard(event.getTargetBoard()); oldBoard = null; - } - else { + } else { LogUtils.debug(mcMMO.p.getLogger(), "Not reverting targetBoard for " + playerName + " - targetBoard was changed by another plugin (Consider disabling the mcMMO scoreboards if you don't want them!)"); } } @@ -411,7 +408,7 @@ public class ScoreboardWrapper { protected void loadObjective(String displayName) { //Unregister objective McMMOScoreboardObjectiveEvent unregisterEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.UNREGISTER_THIS_OBJECTIVE); - if(!unregisterEvent.isCancelled()) { + if (!unregisterEvent.isCancelled()) { try { sidebarObjective.unregister(); } catch (IllegalStateException e) { @@ -419,7 +416,7 @@ public class ScoreboardWrapper { LogUtils.debug(mcMMO.p.getLogger(), "Recovering scoreboard for player: " + player.getName()); - if(mmoPlayer.isDebugMode()) + if (mmoPlayer.isDebugMode()) NotificationManager.sendPlayerInformationChatOnlyPrefixed(player, "Scoreboard.Recovery"); initBoard(); //Start over @@ -429,7 +426,7 @@ public class ScoreboardWrapper { //Register objective McMMOScoreboardObjectiveEvent registerEvent = callObjectiveEvent(ScoreboardObjectiveEventReason.REGISTER_NEW_OBJECTIVE); - if(!registerEvent.isCancelled()) + if (!registerEvent.isCancelled()) sidebarObjective = registerEvent.getTargetBoard().registerNewObjective(ScoreboardManager.SIDEBAR_OBJECTIVE, "dummy", SIDE_OBJECTIVE); if (displayName.length() > 32) { @@ -453,7 +450,7 @@ public class ScoreboardWrapper { * Load new values into the sidebar. */ private void updateSidebar() { - if(updateTask != null) { + if (updateTask != null) { try { updateTask.cancel(); } catch (Exception e) { @@ -477,7 +474,7 @@ public class ScoreboardWrapper { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; switch (sidebarType) { @@ -485,15 +482,14 @@ public class ScoreboardWrapper { break; case SKILL_BOARD: - Validate.notNull(targetSkill); + requireNonNull(targetSkill); if (!SkillTools.isChildSkill(targetSkill)) { int currentXP = mcMMOPlayer.getSkillXpLevel(targetSkill); sidebarObjective.getScore(ScoreboardManager.LABEL_CURRENT_XP).setScore(currentXP); sidebarObjective.getScore(ScoreboardManager.LABEL_REMAINING_XP).setScore(mcMMOPlayer.getXpToLevel(targetSkill) - currentXP); - } - else { + } else { for (PrimarySkillType parentSkill : mcMMO.p.getSkillTools().getChildSkillParents(targetSkill)) { sidebarObjective.getScore(ScoreboardManager.skillLabels.get(parentSkill)).setScore(mcMMOPlayer.getSkillLevel(parentSkill)); } @@ -515,8 +511,7 @@ public class ScoreboardWrapper { cooldownBM.setScore(secondsBM); stopUpdating = (secondsSB == 0 && secondsBM == 0); - } - else { + } else { SuperAbilityType ability = mcMMO.p.getSkillTools().getSuperAbility(targetSkill); Score cooldown = sidebarObjective.getScore(ScoreboardManager.abilityLabelsSkill.get(ability)); int seconds = Math.max(mcMMOPlayer.calculateTimeRemaining(ability), 0); @@ -528,8 +523,7 @@ public class ScoreboardWrapper { if (stopUpdating) { stopCooldownUpdating(); - } - else { + } else { startCooldownUpdating(); } } @@ -550,8 +544,7 @@ public class ScoreboardWrapper { if (anyCooldownsActive) { startCooldownUpdating(); - } - else { + } else { stopCooldownUpdating(); } break; @@ -562,11 +555,9 @@ public class ScoreboardWrapper { if (targetProfile != null) { newProfile = targetProfile; // offline - } - else if (targetPlayer == null) { + } else if (targetPlayer == null) { newProfile = mcMMOPlayer.getProfile(); // self - } - else { + } else { newProfile = UserManager.getPlayer(targetPlayer).getProfile(); // online } diff --git a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java index fd2d240c2..fb5834ad9 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/CombatUtils.java @@ -9,7 +9,6 @@ import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.metadata.MobMetaFlagType; -import com.gmail.nossr50.metadata.MobMetadataService; import com.gmail.nossr50.runnables.skills.AwardCombatXpTask; import com.gmail.nossr50.skills.acrobatics.AcrobaticsManager; import com.gmail.nossr50.skills.archery.ArcheryManager; @@ -37,14 +36,12 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +import static com.gmail.nossr50.util.MobMetadataUtils.hasMobFlag; + public final class CombatUtils { private CombatUtils() {} - private static @NotNull MobMetadataService getMobMetadataService() { - return mcMMO.getMetadataService().getMobMetadataService(); - } - public static boolean isDamageLikelyFromNormalCombat(@NotNull DamageCause damageCause) { return switch (damageCause) { case ENTITY_ATTACK, ENTITY_SWEEP_ATTACK, PROJECTILE -> true; @@ -64,7 +61,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -75,13 +72,12 @@ public final class CombatUtils { mcMMOPlayer.checkAbilityActivation(PrimarySkillType.SWORDS); } - if(target.getHealth() - event.getFinalDamage() > 0) { + if (target.getHealth() - event.getFinalDamage() > 0) { swordsManager.processRupture(target); } //Add Stab Damage - if(swordsManager.canUseStab()) - { + if (swordsManager.canUseStab()) { boostedDamage += (swordsManager.getStabDamage() * mcMMOPlayer.getAttackStrength()); } @@ -89,8 +85,7 @@ public final class CombatUtils { swordsManager.serratedStrikes(target, event.getDamage()); } - if(canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.SWORDS_SWORDS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -101,16 +96,17 @@ public final class CombatUtils { } private static void printFinalDamageDebug(@NotNull Player player, @NotNull EntityDamageByEntityEvent event, @NotNull McMMOPlayer mcMMOPlayer, @Nullable String @Nullable ... extraInfoLines) { - if(mcMMOPlayer.isDebugMode()) { + if (mcMMOPlayer.isDebugMode()) { player.sendMessage("Final Damage value after mcMMO modifiers: "+ event.getFinalDamage()); - if(extraInfoLines != null) { + if (extraInfoLines != null) { for(String str : extraInfoLines) { - if(str != null) + if (str != null) player.sendMessage(str); } } } } + private static void processTridentCombatMelee(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; @@ -121,7 +117,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -135,7 +131,7 @@ public final class CombatUtils { boostedDamage += (tridentsManager.impaleDamageBonus() * mcMMOPlayer.getAttackStrength()); } - if(canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -155,7 +151,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -165,7 +161,7 @@ public final class CombatUtils { boostedDamage += (tridentsManager.impaleDamageBonus() * mcMMOPlayer.getAttackStrength()); } - if(canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK)) { boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.TRIDENTS_TRIDENTS_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -182,7 +178,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { delayArrowMetaCleanup(arrow); return; } @@ -194,7 +190,7 @@ public final class CombatUtils { boostedDamage = mcMMOPlayer.getCrossbowsManager().poweredShot(initialDamage); } - if(canUseLimitBreak(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { + if (canUseLimitBreak(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK)) { boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.CROSSBOWS_CROSSBOWS_LIMIT_BREAK); } @@ -214,6 +210,32 @@ public final class CombatUtils { delayArrowMetaCleanup(arrow); } + private static void processMacesCombat(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { + if (event.getCause() == DamageCause.THORNS) { + return; + } + + double boostedDamage = event.getDamage(); + + McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); + + //Make sure the profiles been loaded + if (mcMMOPlayer == null) { + return; + } + + // MacesManager macesManager = mcMMOPlayer.getMacesManager(); + + if (canUseLimitBreak(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK)) { + boostedDamage += (getLimitBreakDamage(player, target, SubSkillType.MACES_MACES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); + } + + event.setDamage(boostedDamage); + processCombatXP(mcMMOPlayer, target, PrimarySkillType.MACES); + + printFinalDamageDebug(player, event, mcMMOPlayer); + } + private static void processAxeCombat(@NotNull LivingEntity target, @NotNull Player player, @NotNull EntityDamageByEntityEvent event) { if (event.getCause() == DamageCause.THORNS) { return; @@ -224,7 +246,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -240,8 +262,7 @@ public final class CombatUtils { if (axesManager.canImpact(target)) { axesManager.impactCheck(target); - } - else if (axesManager.canGreaterImpact(target)) { + } else if (axesManager.canGreaterImpact(target)) { boostedDamage+=axesManager.greaterImpact(target); } @@ -253,8 +274,7 @@ public final class CombatUtils { boostedDamage+=(axesManager.criticalHit(target, boostedDamage) * mcMMOPlayer.getAttackStrength()); } - if(canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK)) { boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.AXES_AXES_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -274,7 +294,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -296,8 +316,7 @@ public final class CombatUtils { unarmedManager.disarmCheck((Player) target); } - if(canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK)) { boostedDamage+=(getLimitBreakDamage(player, target, SubSkillType.UNARMED_UNARMED_LIMIT_BREAK) * mcMMOPlayer.getAttackStrength()); } @@ -311,11 +330,11 @@ public final class CombatUtils { double initialDamage = event.getDamage(); double boostedDamage = initialDamage; - if(master != null && master.isOnline() && master.isValid()) { + if (master != null && master.isOnline() && master.isValid()) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(master); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { return; } @@ -348,7 +367,7 @@ public final class CombatUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Make sure the profiles been loaded - if(mcMMOPlayer == null) { + if (mcMMOPlayer == null) { delayArrowMetaCleanup(arrow); return; } @@ -370,15 +389,14 @@ public final class CombatUtils { archeryManager.retrieveArrows(target, arrow); } - if(canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) - { + if (canUseLimitBreak(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK)) { boostedDamage+=getLimitBreakDamage(player, target, SubSkillType.ARCHERY_ARCHERY_LIMIT_BREAK); } double distanceMultiplier = ArcheryManager.distanceXpBonusMultiplier(target, arrow); double forceMultiplier = 1.0; //Hacky Fix - some plugins spawn arrows and assign them to players after the ProjectileLaunchEvent fires - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) forceMultiplier = arrow.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0).asDouble(); event.setDamage(boostedDamage); @@ -407,7 +425,7 @@ public final class CombatUtils { } if (target instanceof Player player) { - if(ExperienceConfig.getInstance().isNPCInteractionPrevented()) { + if (ExperienceConfig.getInstance().isNPCInteractionPrevented()) { if (Misc.isNPCEntityExcludingVillagers(target)) { return; } @@ -470,8 +488,7 @@ public final class CombatUtils { processSwordCombat(target, player, event); } - } - else if (ItemUtils.isAxe(heldItem)) { + } else if (ItemUtils.isAxe(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.AXES, target)) { return; } @@ -479,8 +496,7 @@ public final class CombatUtils { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.AXES)) { processAxeCombat(target, player, event); } - } - else if (ItemUtils.isUnarmed(heldItem)) { + } else if (ItemUtils.isUnarmed(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.UNARMED, target)) { return; } @@ -488,8 +504,7 @@ public final class CombatUtils { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.UNARMED)) { processUnarmedCombat(target, player, event); } - } - else if (ItemUtils.isTrident(heldItem)) { + } else if (ItemUtils.isTrident(heldItem)) { if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { return; } @@ -497,6 +512,14 @@ public final class CombatUtils { if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TRIDENTS)) { processTridentCombatMelee(target, player, event); } + } else if (ItemUtils.isMace(heldItem)) { + if (!mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.MACES, target)) { + return; + } + + if (mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.MACES)) { + processMacesCombat(target, player, event); + } } } @@ -510,27 +533,25 @@ public final class CombatUtils { processTamingCombat(target, master, wolf, event); } } - } - else if (painSource instanceof Trident trident) { + } else if (painSource instanceof Trident trident) { ProjectileSource projectileSource = trident.getShooter(); if (projectileSource instanceof Player player) { if (!Misc.isNPCEntityExcludingVillagers(player)) { - if(mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { + if (mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.TRIDENTS, target)) { processTridentCombatRanged(trident, target, player, event); } } } - } - else if (painSource instanceof Arrow arrow) { + } else if (painSource instanceof Arrow arrow) { ProjectileSource projectileSource = arrow.getShooter(); boolean isCrossbow = arrow.isShotFromCrossbow(); if (projectileSource instanceof Player player) { if (!Misc.isNPCEntityExcludingVillagers(player)) { - if(!isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) { + if (!isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.ARCHERY, target)) { processArcheryCombat(target, player, event, arrow); - } else if(isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.CROSSBOWS, target)) { + } else if (isCrossbow && mcMMO.p.getSkillTools().canCombatSkillsTrigger(PrimarySkillType.CROSSBOWS, target)) { processCrossbowsCombat(target, player, event, arrow); } } else { @@ -543,7 +564,7 @@ public final class CombatUtils { && mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.TAMING)) { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; TamingManager tamingManager = mcMMOPlayer.getTamingManager(); @@ -557,11 +578,10 @@ public final class CombatUtils { * This cleans up names from displaying in chat as hearts * @param entity target entity */ - public static void fixNames(@NotNull LivingEntity entity) - { + public static void fixNames(@NotNull LivingEntity entity) { List metadataValue = entity.getMetadata(MetadataConstants.METADATA_KEY_OLD_NAME_KEY); - if(metadataValue.size() <= 0) + if (metadataValue.size() <= 0) return; OldName oldName = (OldName) metadataValue.get(0); @@ -579,7 +599,7 @@ public final class CombatUtils { * @return the RAW damage bonus from Limit Break which is applied before reductions */ public static int getLimitBreakDamage(@NotNull Player attacker, @NotNull LivingEntity defender, @NotNull SubSkillType subSkillType) { - if(defender instanceof Player playerDefender) { + if (defender instanceof Player playerDefender) { return getLimitBreakDamageAgainstQuality(attacker, subSkillType, getArmorQualityLevel(playerDefender)); } else { return getLimitBreakDamageAgainstQuality(attacker, subSkillType, 1000); @@ -597,11 +617,11 @@ public final class CombatUtils { public static int getLimitBreakDamageAgainstQuality(@NotNull Player attacker, @NotNull SubSkillType subSkillType, int armorQualityLevel) { int rawDamageBoost = RankUtils.getRank(attacker, subSkillType); - if(armorQualityLevel <= 4) { + if (armorQualityLevel <= 4) { rawDamageBoost *= .25; //75% Nerf - } else if(armorQualityLevel <= 8) { + } else if (armorQualityLevel <= 8) { rawDamageBoost *= .50; //50% Nerf - } else if(armorQualityLevel <= 12) { + } else if (armorQualityLevel <= 12) { rawDamageBoost *= .75; //25% Nerf } @@ -617,7 +637,7 @@ public final class CombatUtils { int armorQualityLevel = 0; for(ItemStack itemStack : defender.getInventory().getArmorContents()) { - if(itemStack != null) { + if (itemStack != null) { armorQualityLevel += getArmorQuality(itemStack); } } @@ -640,7 +660,7 @@ public final class CombatUtils { * @return true if the player has access to the limit break */ public static boolean canUseLimitBreak(@NotNull Player player, LivingEntity target, @NotNull SubSkillType subSkillType) { - if(target instanceof Player || mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { + if (target instanceof Player || mcMMO.p.getAdvancedConfig().canApplyLimitBreakPVE()) { return RankUtils.hasUnlockedSubskill(player, subSkillType) && Permissions.isSubSkillEnabled(player, subSkillType); } else { @@ -793,7 +813,7 @@ public final class CombatUtils { McMMOPlayer mmoAttacker = UserManager.getPlayer(attacker); - if(mmoAttacker != null) { + if (mmoAttacker != null) { mmoAttacker.getSwordsManager().processRupture(livingEntity); } @@ -854,53 +874,43 @@ public final class CombatUtils { && SkillUtils.cooldownExpired(mcMMOPlayer.getRespawnATS(), Misc.PLAYER_RESPAWN_COOLDOWN_SECONDS)) { baseXP = 20 * ExperienceConfig.getInstance().getPlayerVersusPlayerXP(); } - } - else { + } else { if (mcMMO.getModManager().isCustomEntity(target)) { baseXP = mcMMO.getModManager().getEntity(target).getXpMultiplier(); - } - else if (target instanceof Animals) { + } else if (target instanceof Animals) { EntityType type = target.getType(); baseXP = ExperienceConfig.getInstance().getAnimalsXP(type); - } - else if (target instanceof Monster) - { + } else if (target instanceof Monster) { EntityType type = target.getType(); baseXP = ExperienceConfig.getInstance().getCombatXP(type); - } - else { + } else { EntityType type = target.getType(); if (ExperienceConfig.getInstance().hasCombatXP(type)) { - if (type == EntityType.IRON_GOLEM) - { + if (type == EntityType.IRON_GOLEM) { if (!((IronGolem) target).isPlayerCreated()) { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } - } - else - { + } else { baseXP = ExperienceConfig.getInstance().getCombatXP(type); } - } - else - { + } else { baseXP = 1.0; mcMMO.getModManager().addCustomEntity(target); } } - if(getMobMetadataService().hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { + if (hasMobFlag(MobMetaFlagType.COTW_SUMMONED_MOB, target)) { baseXP = 0; - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { + } else if (hasMobFlag(MobMetaFlagType.MOB_SPAWNER_MOB, target) || target.hasMetadata("ES")) { baseXP *= ExperienceConfig.getInstance().getSpawnedMobXpMultiplier(); - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.NETHER_PORTAL_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getNetherPortalXpMultiplier(); - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.EGG_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.EGG_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getEggXpMultiplier(); - } else if (getMobMetadataService().hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.PLAYER_BRED_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getBredMobXpMultiplier(); - } else if(getMobMetadataService().hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) { + } else if (hasMobFlag(MobMetaFlagType.PLAYER_TAMED_MOB, target)) { baseXP *= ExperienceConfig.getInstance().getTamedMobXpMultiplier(); } @@ -925,15 +935,17 @@ public final class CombatUtils { private static boolean shouldBeAffected(@NotNull Player player, @NotNull Entity entity) { if (entity instanceof Player defender) { //TODO: NPC Interaction? - if(UserManager.getPlayer(defender) == null) + if (UserManager.getPlayer(defender) == null) return true; if (!defender.getWorld().getPVP() || defender == player || UserManager.getPlayer(defender).getGodMode()) { return false; } - if ((mcMMO.p.getPartyManager().inSameParty(player, defender) || mcMMO.p.getPartyManager().areAllies(player, defender)) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { - return false; + if (mcMMO.p.getPartyConfig().isPartyEnabled()) { + if ((mcMMO.p.getPartyManager().inSameParty(player, defender) || mcMMO.p.getPartyManager().areAllies(player, defender)) && !(Permissions.friendlyFire(player) && Permissions.friendlyFire(defender))) { + return false; + } } // Vanished players should not be able to get hit by AoE effects @@ -983,7 +995,7 @@ public final class CombatUtils { if (tamer instanceof Player owner) { - return (owner == attacker || mcMMO.p.getPartyManager().inSameParty(attacker, owner) || mcMMO.p.getPartyManager().areAllies(attacker, owner)); + return (owner == attacker || (mcMMO.p.getPartyConfig().isPartyEnabled() && (mcMMO.p.getPartyManager().inSameParty(attacker, owner) || mcMMO.p.getPartyManager().areAllies(attacker, owner)))); } } @@ -1001,22 +1013,17 @@ public final class CombatUtils { if (ItemUtils.isWoodTool(inHand)) { tier = 1; - } - else if (ItemUtils.isStoneTool(inHand)) { + } else if (ItemUtils.isStoneTool(inHand)) { tier = 2; - } - else if (ItemUtils.isIronTool(inHand)) { + } else if (ItemUtils.isIronTool(inHand)) { tier = 3; - } - else if (ItemUtils.isGoldTool(inHand)) { + } else if (ItemUtils.isGoldTool(inHand)) { tier = 1; - } - else if (ItemUtils.isDiamondTool(inHand)) { + } else if (ItemUtils.isDiamondTool(inHand)) { tier = 4; } else if (ItemUtils.isNetheriteTool(inHand)) { tier = 5; - } - else if (mcMMO.getModManager().isCustomTool(inHand)) { + } else if (mcMMO.getModManager().isCustomTool(inHand)) { tier = mcMMO.getModManager().getTool(inHand).getTier(); } @@ -1042,7 +1049,7 @@ public final class CombatUtils { public static void modifyMoveSpeed(@NotNull LivingEntity livingEntity, double multiplier) { AttributeInstance attributeInstance = livingEntity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED); - if(attributeInstance != null) { + if (attributeInstance != null) { double normalSpeed = attributeInstance.getBaseValue(); attributeInstance.setBaseValue(normalSpeed * multiplier); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java index 48265d03f..c0e17bbe8 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ParticleEffectUtils.java @@ -3,7 +3,7 @@ package com.gmail.nossr50.util.skills; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.sounds.SoundManager; import com.gmail.nossr50.util.sounds.SoundType; -import org.apache.commons.lang.math.RandomUtils; +import org.apache.commons.lang3.RandomUtils; import org.bukkit.Effect; import org.bukkit.Location; import org.bukkit.Material; @@ -42,31 +42,22 @@ public final class ParticleEffectUtils { double offSetVal = 0.3D; - switch(RandomUtils.nextInt(10)) { - - case 0: - return new Location(world, x - offSetVal, y, z); - case 1: - return new Location(world, x + offSetVal, y, z); - case 2: - return new Location(world, x, y + offSetVal, z); - case 3: - return new Location(world, x, y - offSetVal, z); - case 4: Location locE = new Location(world, x, y, z + offSetVal); - return new Location(world, x, y, z - offSetVal); - case 5: - return new Location(world, x + offSetVal, y, z + offSetVal); - case 6: - return new Location(world, x - offSetVal, y, z - offSetVal); - case 7: - return new Location(world, x - offSetVal, y - offSetVal, z - offSetVal); - case 8: - return new Location(world, x + offSetVal, y - offSetVal, z + offSetVal); - case 9: - return new Location(world, x - offSetVal, y + offSetVal, z - offSetVal); - default: - return new Location(world, x + offSetVal, y + offSetVal, z - offSetVal); - } + return switch (RandomUtils.nextInt(0, 10)) { + case 0 -> new Location(world, x - offSetVal, y, z); + case 1 -> new Location(world, x + offSetVal, y, z); + case 2 -> new Location(world, x, y + offSetVal, z); + case 3 -> new Location(world, x, y - offSetVal, z); + case 4 -> { + Location locE = new Location(world, x, y, z + offSetVal); + yield new Location(world, x, y, z - offSetVal); + } + case 5 -> new Location(world, x + offSetVal, y, z + offSetVal); + case 6 -> new Location(world, x - offSetVal, y, z - offSetVal); + case 7 -> new Location(world, x - offSetVal, y - offSetVal, z - offSetVal); + case 8 -> new Location(world, x + offSetVal, y - offSetVal, z + offSetVal); + case 9 -> new Location(world, x - offSetVal, y + offSetVal, z - offSetVal); + default -> new Location(world, x + offSetVal, y + offSetVal, z - offSetVal); + }; } public static void playDodgeEffect(Player player) { @@ -82,7 +73,7 @@ public final class ParticleEffectUtils { return; } - if(location.getWorld() == null) + if (location.getWorld() == null) return; location.getWorld().playEffect(location, Effect.MOBSPAWNER_FLAMES, 1); @@ -91,7 +82,7 @@ public final class ParticleEffectUtils { public static void playSmokeEffect(Location location) { World world = location.getWorld(); - if(world == null) + if (world == null) return; // Have to do it this way, because not all block directions are valid for smoke diff --git a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java index 2d83cb063..44320b37a 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/PerksUtils.java @@ -1,6 +1,7 @@ package com.gmail.nossr50.util.skills; import com.gmail.nossr50.config.experience.ExperienceConfig; +import com.gmail.nossr50.datatypes.player.McMMOPlayer; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import com.gmail.nossr50.events.skills.SkillActivationPerkEvent; import com.gmail.nossr50.util.Permissions; @@ -18,11 +19,9 @@ public final class PerksUtils { public static int handleCooldownPerks(Player player, int cooldown) { if (Permissions.halvedCooldowns(player)) { cooldown *= 0.5; - } - else if (Permissions.thirdedCooldowns(player)) { + } else if (Permissions.thirdedCooldowns(player)) { cooldown *= (2.0 / 3.0); - } - else if (Permissions.quarteredCooldowns(player)) { + } else if (Permissions.quarteredCooldowns(player)) { cooldown *= 0.75; } @@ -36,11 +35,9 @@ public final class PerksUtils { if (Permissions.twelveSecondActivationBoost(player)) { ticks += 12; - } - else if (Permissions.eightSecondActivationBoost(player)) { + } else if (Permissions.eightSecondActivationBoost(player)) { ticks += 8; - } - else if (Permissions.fourSecondActivationBoost(player)) { + } else if (Permissions.fourSecondActivationBoost(player)) { ticks += 4; } @@ -53,37 +50,30 @@ public final class PerksUtils { double modifier = 1.0F; if (Permissions.customXpBoost(player, skill)) { - if(UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { + if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.DARK_GRAY + "XP Perk Multiplier IS CUSTOM! "); } modifier = ExperienceConfig.getInstance().getCustomXpPerkBoost(); - } - else if (Permissions.quadrupleXp(player, skill)) { + } else if (Permissions.quadrupleXp(player, skill)) { modifier = 4; - } - else if (Permissions.tripleXp(player, skill)) { + } else if (Permissions.tripleXp(player, skill)) { modifier = 3; - } - else if (Permissions.doubleAndOneHalfXp(player, skill)) { + } else if (Permissions.doubleAndOneHalfXp(player, skill)) { modifier = 2.5; - } - else if (Permissions.doubleXp(player, skill)) { + } else if (Permissions.doubleXp(player, skill)) { modifier = 2; - } - else if (Permissions.oneAndOneHalfXp(player, skill)) { + } else if (Permissions.oneAndOneHalfXp(player, skill)) { modifier = 1.5; - } - else if (Permissions.oneAndAQuarterXp(player, skill)) { + } else if (Permissions.oneAndAQuarterXp(player, skill)) { modifier = 1.25; - } - else if (Permissions.oneAndOneTenthXp(player, skill)) { + } else if (Permissions.oneAndOneTenthXp(player, skill)) { modifier = 1.1; } float modifiedXP = (float) (xp * modifier); - if(UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { + if (UserManager.getPlayer(player) != null && UserManager.getPlayer(player).isDebugMode()) { player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP Perk Multiplier - " + ChatColor.GOLD + modifier); player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "Original XP before perk boosts " + ChatColor.RED + (double) xp); player.sendMessage(ChatColor.GOLD + "[DEBUG] " + ChatColor.RESET + "XP AFTER PERKS " + ChatColor.DARK_RED + modifiedXP); @@ -106,4 +96,19 @@ public final class PerksUtils { return NORMAL_SKILL_ACTIVATION_CHANCE; } + + /** + * Calculate activation chance for a skill. + * + * @param mmoPlayer Player to check the activation chance for + * @param skill PrimarySkillType to check the activation chance of + * @return the activation chance with "lucky perk" accounted for + */ + public static int handleLuckyPerks(McMMOPlayer mmoPlayer, PrimarySkillType skill) { + if (Permissions.lucky(mmoPlayer.getPlayer(), skill)) { + return LUCKY_SKILL_ACTIVATION_CHANCE; + } + + return NORMAL_SKILL_ACTIVATION_CHANCE; + } } diff --git a/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java b/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java index f64bac7a3..4835afc47 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/ProjectileUtils.java @@ -29,54 +29,54 @@ public class ProjectileUtils { */ // TODO: Add test public static void cleanupProjectileMetadata(@NotNull Arrow arrow) { - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, mcMMO.p); } - if(arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT)) { + if (arrow.hasMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT)) { arrow.removeMetadata(MetadataConstants.METADATA_KEY_BOUNCE_COUNT, mcMMO.p); } } public static void copyArrowMetadata(@NotNull Plugin pluginRef, @NotNull Arrow arrowToCopy, @NotNull Arrow newArrow) { - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_INF_ARROW)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_INF_ARROW, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_INF_ARROW).get(0)); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE, new FixedMetadataValue(pluginRef, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_BOW_FORCE).get(0).asDouble())); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_ARROW_DISTANCE).get(0)); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_SPAWNED_ARROW).get(0)); } - if(arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { + if (arrowToCopy.hasMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW)) { newArrow.setMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW, arrowToCopy.getMetadata(MetadataConstants.METADATA_KEY_MULTI_SHOT_ARROW).get(0)); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java index e06497128..398cb579b 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/RankUtils.java @@ -27,25 +27,22 @@ public class RankUtils { * @param primarySkillType the skill to check * @param newLevel the new level of this skill */ - public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) - { - for(SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType)) - { + public static void executeSkillUnlockNotifications(Plugin plugin, McMMOPlayer mcMMOPlayer, PrimarySkillType primarySkillType, int newLevel) { + for(SubSkillType subSkillType : mcMMO.p.getSkillTools().getSubSkills(primarySkillType)) { int playerRankInSkill = getRank(mcMMOPlayer.getPlayer(), subSkillType); HashMap innerMap = subSkillRanks.get(subSkillType.toString()); //If the skill doesn't have registered ranks gtfo - if(innerMap == null || innerMap.get(playerRankInSkill) == null) + if (innerMap == null || innerMap.get(playerRankInSkill) == null) continue; //Don't send notifications if the player lacks the permission node - if(!Permissions.isSubSkillEnabled(mcMMOPlayer.getPlayer(), subSkillType)) + if (!Permissions.isSubSkillEnabled(mcMMOPlayer.getPlayer(), subSkillType)) continue; //The players level is the exact level requirement for this skill - if(newLevel == innerMap.get(playerRankInSkill)) - { + if (newLevel == innerMap.get(playerRankInSkill)) { SkillUnlockNotificationTask skillUnlockNotificationTask = new SkillUnlockNotificationTask(mcMMOPlayer, subSkillType, newLevel); mcMMO.p.getFoliaLib().getImpl().runAtEntityLater(mcMMOPlayer.getPlayer(), skillUnlockNotificationTask, (count * 100L)); @@ -58,17 +55,14 @@ public class RankUtils { /** * Reset the interval between skill unlock notifications */ - public static void resetUnlockDelayTimer() - { + public static void resetUnlockDelayTimer() { count = 0; } /* NEW SYSTEM */ - private static void addRanks(AbstractSubSkill abstractSubSkill) - { + private static void addRanks(AbstractSubSkill abstractSubSkill) { //Fill out the rank array - for(int i = 0; i < abstractSubSkill.getNumRanks(); i++) - { + for(int i = 0; i < abstractSubSkill.getNumRanks(); i++) { //This adds the highest ranks first addRank(abstractSubSkill, abstractSubSkill.getNumRanks()-i); @@ -77,11 +71,9 @@ public class RankUtils { } } - private static void addRanks(SubSkillType subSkillType) - { + private static void addRanks(SubSkillType subSkillType) { //Fill out the rank array - for(int i = 0; i < subSkillType.getNumRanks(); i++) - { + for(int i = 0; i < subSkillType.getNumRanks(); i++) { //This adds the highest ranks first addRank(subSkillType, subSkillType.getNumRanks()-i); @@ -93,15 +85,12 @@ public class RankUtils { /** * Populates the ranks for every skill we know about */ - public static void populateRanks() - { - for(SubSkillType subSkillType : SubSkillType.values()) - { + public static void populateRanks() { + for(SubSkillType subSkillType : SubSkillType.values()) { addRanks(subSkillType); } - for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) - { + for(AbstractSubSkill abstractSubSkill : InteractionManager.getSubSkillList()) { addRanks(abstractSubSkill); } } @@ -112,8 +101,7 @@ public class RankUtils { * @param subSkillType the target subskill * @return true if the player has at least one rank in the skill */ - public static boolean hasUnlockedSubskill(Player player, SubSkillType subSkillType) - { + public static boolean hasUnlockedSubskill(Player player, SubSkillType subSkillType) { int curRank = getRank(player, subSkillType); //-1 means the skill has no unlockable levels and is therefor unlocked @@ -126,8 +114,7 @@ public class RankUtils { * @param abstractSubSkill the target subskill * @return true if the player has at least one rank in the skill */ - public static boolean hasUnlockedSubskill(Player player, AbstractSubSkill abstractSubSkill) - { + public static boolean hasUnlockedSubskill(Player player, AbstractSubSkill abstractSubSkill) { int curRank = getRank(player, abstractSubSkill); //-1 means the skill has no unlockable levels and is therefor unlocked @@ -141,8 +128,7 @@ public class RankUtils { * @param subSkillType the target subskill * @return true if the player is at least that rank in this subskill */ - public static boolean hasReachedRank(int rank, Player player, SubSkillType subSkillType) - { + public static boolean hasReachedRank(int rank, Player player, SubSkillType subSkillType) { return getRank(player, subSkillType) >= rank; } @@ -153,8 +139,7 @@ public class RankUtils { * @param abstractSubSkill the target subskill * @return true if the player is at least that rank in this subskill */ - public static boolean hasReachedRank(int rank, Player player, AbstractSubSkill abstractSubSkill) - { + public static boolean hasReachedRank(int rank, Player player, AbstractSubSkill abstractSubSkill) { return getRank(player, abstractSubSkill) >= rank; } @@ -164,8 +149,7 @@ public class RankUtils { * @param subSkillType Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(McMMOPlayer mmoPlayer, SubSkillType subSkillType) - { + public static int getRank(McMMOPlayer mmoPlayer, SubSkillType subSkillType) { return getRank(mmoPlayer.getPlayer(), subSkillType); } @@ -175,41 +159,39 @@ public class RankUtils { * @param subSkillType Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(Player player, SubSkillType subSkillType) - { + public static int getRank(Player player, SubSkillType subSkillType) { String skillName = subSkillType.toString(); int numRanks = subSkillType.getNumRanks(); - if(subSkillRanks == null) + if (subSkillRanks == null) subSkillRanks = new HashMap<>(); - if(numRanks == 0) + if (numRanks == 0) return -1; //-1 Means the skill doesn't have ranks - if(subSkillRanks.get(skillName) == null && numRanks > 0) + if (subSkillRanks.get(skillName) == null && numRanks > 0) addRanks(subSkillType); //Get our rank map HashMap rankMap = subSkillRanks.get(skillName); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return 0; //Skill level of parent skill int currentSkillLevel = UserManager.getPlayer(player).getSkillLevel(subSkillType.getParentSkill()); - for(int i = 0; i < numRanks; i++) - { + for(int i = 0; i < numRanks; i++) { //Compare against the highest to lowest rank in that order int rank = numRanks-i; int unlockLevel = getRankUnlockLevel(subSkillType, rank); //If we check all ranks and still cannot unlock the skill, we return rank 0 - if(rank == 0) + if (rank == 0) return 0; //True if our skill level can unlock the current rank - if(currentSkillLevel >= unlockLevel) + if (currentSkillLevel >= unlockLevel) return rank; } @@ -222,41 +204,39 @@ public class RankUtils { * @param abstractSubSkill Target subskill * @return The rank the player currently has achieved in this skill. -1 for skills without ranks. */ - public static int getRank(Player player, AbstractSubSkill abstractSubSkill) - { + public static int getRank(Player player, AbstractSubSkill abstractSubSkill) { String skillName = abstractSubSkill.getConfigKeyName(); int numRanks = abstractSubSkill.getNumRanks(); - if(subSkillRanks == null) + if (subSkillRanks == null) subSkillRanks = new HashMap<>(); - if(numRanks == 0) + if (numRanks == 0) return -1; //-1 Means the skill doesn't have ranks - if(subSkillRanks.get(skillName) == null && numRanks > 0) + if (subSkillRanks.get(skillName) == null && numRanks > 0) addRanks(abstractSubSkill); //Get our rank map HashMap rankMap = subSkillRanks.get(skillName); - if(UserManager.getPlayer(player) == null) + if (UserManager.getPlayer(player) == null) return 0; //Skill level of parent skill int currentSkillLevel = UserManager.getPlayer(player).getSkillLevel(abstractSubSkill.getPrimarySkill()); - for(int i = 0; i < numRanks; i++) - { + for(int i = 0; i < numRanks; i++) { //Compare against the highest to lowest rank in that order int rank = numRanks-i; int unlockLevel = getRankUnlockLevel(abstractSubSkill, rank); //If we check all ranks and still cannot unlock the skill, we return rank 0 - if(rank == 0) + if (rank == 0) return 0; //True if our skill level can unlock the current rank - if(currentSkillLevel >= unlockLevel) + if (currentSkillLevel >= unlockLevel) return rank; } @@ -268,8 +248,7 @@ public class RankUtils { * @param abstractSubSkill The subskill to add ranks for * @param rank The rank to add */ - private static void addRank(AbstractSubSkill abstractSubSkill, int rank) - { + private static void addRank(AbstractSubSkill abstractSubSkill, int rank) { initMaps(abstractSubSkill.getConfigKeyName()); HashMap rankMap = subSkillRanks.get(abstractSubSkill.getConfigKeyName()); @@ -278,8 +257,7 @@ public class RankUtils { } @Deprecated - private static void addRank(SubSkillType subSkillType, int rank) - { + private static void addRank(SubSkillType subSkillType, int rank) { initMaps(subSkillType.toString()); HashMap rankMap = subSkillRanks.get(subSkillType.toString()); @@ -300,13 +278,11 @@ public class RankUtils { * @param rank The target rank * @return The level at which this rank unlocks */ - public static int getRankUnlockLevel(SubSkillType subSkillType, int rank) - { + public static int getRankUnlockLevel(SubSkillType subSkillType, int rank) { return RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, rank); } - public static int getRankUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) - { + public static int getRankUnlockLevel(AbstractSubSkill abstractSubSkill, int rank) { return RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, rank); } @@ -315,8 +291,7 @@ public class RankUtils { * @param subSkillType target subskill * @return The unlock requirements for rank 1 in this skill */ - public static int getUnlockLevel(SubSkillType subSkillType) - { + public static int getUnlockLevel(SubSkillType subSkillType) { return RankConfig.getInstance().getSubSkillUnlockLevel(subSkillType, 1); } @@ -325,8 +300,7 @@ public class RankUtils { * @param abstractSubSkill target subskill * @return The unlock requirements for rank 1 in this skill */ - public static int getUnlockLevel(AbstractSubSkill abstractSubSkill) - { + public static int getUnlockLevel(AbstractSubSkill abstractSubSkill) { return RankConfig.getInstance().getSubSkillUnlockLevel(abstractSubSkill, 1); } @@ -335,13 +309,11 @@ public class RankUtils { * @param subSkillType target subskill * @return the last rank of a subskill */ - public static int getHighestRank(SubSkillType subSkillType) - { + public static int getHighestRank(SubSkillType subSkillType) { return subSkillType.getNumRanks(); } - public static String getHighestRankStr(SubSkillType subSkillType) - { + public static String getHighestRankStr(SubSkillType subSkillType) { return String.valueOf(subSkillType.getNumRanks()); } @@ -350,13 +322,11 @@ public class RankUtils { * @param abstractSubSkill target subskill * @return the last rank of a subskill */ - public static int getHighestRank(AbstractSubSkill abstractSubSkill) - { + public static int getHighestRank(AbstractSubSkill abstractSubSkill) { return abstractSubSkill.getNumRanks(); } - public static int getSuperAbilityUnlockRequirement(SuperAbilityType superAbilityType) - { + public static int getSuperAbilityUnlockRequirement(SuperAbilityType superAbilityType) { return getRankUnlockLevel(superAbilityType.getSubSkillTypeDefinition(), 1); } diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java index 39ddfbd24..151c7e649 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillTools.java @@ -69,7 +69,7 @@ public class SkillTools { for(SubSkillType subSkillType : SubSkillType.values()) { String[] splitSubSkillName = subSkillType.toString().split("_"); - if(primarySkillType1.toString().equalsIgnoreCase(splitSubSkillName[0])) { + if (primarySkillType1.toString().equalsIgnoreCase(splitSubSkillName[0])) { //Parent Skill Found tempSubParentMap.put(subSkillType, primarySkillType1); } @@ -127,7 +127,7 @@ public class SkillTools { PrimarySkillType parent = getSuperAbilityParent(superAbilityType); tempAbilityParentRelationshipMap.put(superAbilityType, parent); - if(superAbilityType != SuperAbilityType.BLAST_MINING) { + if (superAbilityType != SuperAbilityType.BLAST_MINING) { //This map is used only for abilities that have a tool readying phase, so blast mining is ignored tempMainActivatedAbilityChildMap.put(parent, superAbilityType); } @@ -198,6 +198,7 @@ public class SkillTools { case SUPER_SHOTGUN -> PrimarySkillType.CROSSBOWS; case TRIDENTS_SUPER_ABILITY -> PrimarySkillType.TRIDENTS; case EXPLOSIVE_SHOT -> PrimarySkillType.ARCHERY; + case MACES_SUPER_ABILITY -> PrimarySkillType.MACES; }; } @@ -295,7 +296,7 @@ public class SkillTools { } public SuperAbilityType getSuperAbility(PrimarySkillType primarySkillType) { - if(mainActivatedAbilityChildMap.get(primarySkillType) == null) + if (mainActivatedAbilityChildMap.get(primarySkillType) == null) return null; return mainActivatedAbilityChildMap.get(primarySkillType); diff --git a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java index b0d406ae6..a6186d369 100644 --- a/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java +++ b/src/main/java/com/gmail/nossr50/util/skills/SkillUtils.java @@ -10,7 +10,7 @@ import com.gmail.nossr50.datatypes.skills.SubSkillType; import com.gmail.nossr50.datatypes.skills.SuperAbilityType; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.metadata.ItemMetadataService; +import com.gmail.nossr50.util.ItemMetadataUtils; import com.gmail.nossr50.util.ItemUtils; import com.gmail.nossr50.util.Misc; import com.gmail.nossr50.util.Permissions; @@ -20,7 +20,6 @@ import com.gmail.nossr50.util.text.StringUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.Recipe; @@ -28,12 +27,14 @@ import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.ShapelessRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Iterator; +import static com.gmail.nossr50.util.ItemMetadataUtils.*; +import static com.gmail.nossr50.util.PotionEffectUtil.getHastePotionEffectType; + public final class SkillUtils { /** * This is a static utility class, therefore we don't want any instances of @@ -60,8 +61,7 @@ public final class SkillUtils { int length; - if(abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { length = (int) Math.min(abilityLengthCap, 2 + (skillValue / abilityLengthVar)); } else { length = 2 + (int) (skillValue / abilityLengthVar); @@ -141,30 +141,25 @@ public final class SkillUtils { if (HiddenConfig.getInstance().useEnchantmentBuffs()) { ItemStack heldItem = player.getInventory().getItemInMainHand(); - if(heldItem == null) + if (heldItem == null) return; if (!ItemUtils.canBeSuperAbilityDigBoosted(heldItem)) { return; } - int originalDigSpeed = heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED); - - //Add dig speed - - //Lore no longer gets added, no point to it afaik - //ItemUtils.addAbilityLore(heldItem); //lore can be a secondary failsafe for 1.13 and below - ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(Enchantment.DIG_SPEED)); + int originalDigSpeed = heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency()); + ItemUtils.addDigSpeedToItem(heldItem, heldItem.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getEfficiency())); //1.13.2+ will have persistent metadata for this item - mcMMO.getMetadataService().getItemMetadataService().setSuperAbilityBoostedItem(heldItem, originalDigSpeed); + ItemMetadataUtils.setSuperAbilityBoostedItem(heldItem, originalDigSpeed); } else { int duration = 0; int amplifier = 0; - if (player.hasPotionEffect(PotionEffectType.FAST_DIGGING)) { + if (player.hasPotionEffect(getHastePotionEffectType())) { for (PotionEffect effect : player.getActivePotionEffects()) { - if (effect.getType() == PotionEffectType.FAST_DIGGING) { + if (effect.getType() == getHastePotionEffectType()) { duration = effect.getDuration(); amplifier = effect.getAmplifier(); break; @@ -175,7 +170,7 @@ public final class SkillUtils { McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); //Not Loaded - if(mcMMOPlayer == null) + if (mcMMOPlayer == null) return; PrimarySkillType skill = mcMMOPlayer.getAbilityMode(SuperAbilityType.SUPER_BREAKER) ? PrimarySkillType.MINING : PrimarySkillType.EXCAVATION; @@ -185,8 +180,7 @@ public final class SkillUtils { int ticks; - if(abilityLengthCap > 0) - { + if (abilityLengthCap > 0) { ticks = PerksUtils.handleActivationPerks(player, Math.min(abilityLengthCap, 2 + (mcMMOPlayer.getSkillLevel(skill) / abilityLengthVar)), mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; } else { @@ -194,7 +188,7 @@ public final class SkillUtils { mcMMO.p.getSkillTools().getSuperAbilityMaxLength(mcMMO.p.getSkillTools().getSuperAbility(skill))) * Misc.TICK_CONVERSION_FACTOR; } - PotionEffect abilityBuff = new PotionEffect(PotionEffectType.FAST_DIGGING, duration + ticks, amplifier + 10); + PotionEffect abilityBuff = new PotionEffect(getHastePotionEffectType(), duration + ticks, amplifier + 10); player.addPotionEffect(abilityBuff, true); } } @@ -206,30 +200,28 @@ public final class SkillUtils { } public static void removeAbilityBuff(@Nullable ItemStack itemStack) { - if(itemStack == null) + if (itemStack == null) return; - if(!ItemUtils.canBeSuperAbilityDigBoosted(itemStack)) + if (!ItemUtils.canBeSuperAbilityDigBoosted(itemStack)) return; //1.13.2+ will have persistent metadata for this itemStack - ItemMetadataService itemMetadataService = mcMMO.getMetadataService().getItemMetadataService(); - - if(itemMetadataService.isLegacyAbilityTool(itemStack)) { + if (isLegacyAbilityTool(itemStack)) { ItemMeta itemMeta = itemStack.getItemMeta(); - if(itemMeta != null) { + if (itemMeta != null) { // This is safe to call without prior checks. - itemMeta.removeEnchant(Enchantment.DIG_SPEED); + itemMeta.removeEnchant(mcMMO.p.getEnchantmentMapper().getEfficiency()); itemStack.setItemMeta(itemMeta); ItemUtils.removeAbilityLore(itemStack); } } - if(itemMetadataService.isSuperAbilityBoosted(itemStack)) { - itemMetadataService.removeBonusDigSpeedOnSuperAbilityTool(itemStack); + if (isSuperAbilityBoosted(itemStack)) { + removeBonusDigSpeedOnSuperAbilityTool(itemStack); } } @@ -245,13 +237,13 @@ public final class SkillUtils { * @param maxDamageModifier the amount to adjust the max damage by */ public static void handleDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) { - if(itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { + if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { return; } Material type = itemStack.getType(); short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability(); - durabilityModifier = (int) Math.min(durabilityModifier / (itemStack.getEnchantmentLevel(Enchantment.DURABILITY) + 1), maxDurability * maxDamageModifier); + durabilityModifier = (int) Math.min(durabilityModifier / (itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1), maxDurability * maxDamageModifier); itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); } @@ -275,13 +267,13 @@ public final class SkillUtils { * @param maxDamageModifier the amount to adjust the max damage by */ public static void handleArmorDurabilityChange(ItemStack itemStack, double durabilityModifier, double maxDamageModifier) { - if(itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { + if (itemStack.hasItemMeta() && itemStack.getItemMeta().isUnbreakable()) { return; } Material type = itemStack.getType(); short maxDurability = mcMMO.getRepairableManager().isRepairable(type) ? mcMMO.getRepairableManager().getRepairable(type).getMaximumDurability() : type.getMaxDurability(); - durabilityModifier = (int) Math.min(durabilityModifier * (0.6 + 0.4/ (itemStack.getEnchantmentLevel(Enchantment.DURABILITY) + 1)), maxDurability * maxDamageModifier); + durabilityModifier = (int) Math.min(durabilityModifier * (0.6 + 0.4/ (itemStack.getEnchantmentLevel(mcMMO.p.getEnchantmentMapper().getUnbreaking()) + 1)), maxDurability * maxDamageModifier); itemStack.setDurability((short) Math.min(itemStack.getDurability() + durabilityModifier, maxDurability)); } @@ -290,26 +282,19 @@ public final class SkillUtils { public static Material getRepairAndSalvageItem(@NotNull ItemStack inHand) { if (ItemUtils.isDiamondTool(inHand) || ItemUtils.isDiamondArmor(inHand)) { return Material.DIAMOND; - } - else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) { + } else if (ItemUtils.isGoldTool(inHand) || ItemUtils.isGoldArmor(inHand)) { return Material.GOLD_INGOT; - } - else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) { + } else if (ItemUtils.isIronTool(inHand) || ItemUtils.isIronArmor(inHand)) { return Material.IRON_INGOT; - } - else if (ItemUtils.isStoneTool(inHand)) { + } else if (ItemUtils.isStoneTool(inHand)) { return Material.COBBLESTONE; - } - else if (ItemUtils.isWoodTool(inHand)) { + } else if (ItemUtils.isWoodTool(inHand)) { return Material.OAK_WOOD; - } - else if (ItemUtils.isLeatherArmor(inHand)) { + } else if (ItemUtils.isLeatherArmor(inHand)) { return Material.LEATHER; - } - else if (ItemUtils.isStringTool(inHand)) { + } else if (ItemUtils.isStringTool(inHand)) { return Material.STRING; - } - else { + } else { return null; } } @@ -321,7 +306,7 @@ public final class SkillUtils { public static int getRepairAndSalvageQuantities(Material itemMaterial, Material recipeMaterial) { int quantity = 0; - if(mcMMO.getMaterialMapStore().isNetheriteTool(itemMaterial) || mcMMO.getMaterialMapStore().isNetheriteArmor(itemMaterial)) { + if (mcMMO.getMaterialMapStore().isNetheriteTool(itemMaterial) || mcMMO.getMaterialMapStore().isNetheriteArmor(itemMaterial)) { //One netherite bar requires 4 netherite scraps return 4; } @@ -329,10 +314,10 @@ public final class SkillUtils { for(Iterator recipeIterator = Bukkit.getServer().recipeIterator(); recipeIterator.hasNext();) { Recipe bukkitRecipe = recipeIterator.next(); - if(bukkitRecipe.getResult().getType() != itemMaterial) + if (bukkitRecipe.getResult().getType() != itemMaterial) continue; - if(bukkitRecipe instanceof ShapelessRecipe) { + if (bukkitRecipe instanceof ShapelessRecipe) { for (ItemStack ingredient : ((ShapelessRecipe) bukkitRecipe).getIngredientList()) { if (ingredient != null && (recipeMaterial == null || ingredient.getType() == recipeMaterial) @@ -340,7 +325,7 @@ public final class SkillUtils { quantity += ingredient.getAmount(); } } - } else if(bukkitRecipe instanceof ShapedRecipe) { + } else if (bukkitRecipe instanceof ShapedRecipe) { for (ItemStack ingredient : ((ShapedRecipe) bukkitRecipe).getIngredientMap().values()) { if (ingredient != null && (recipeMaterial == null || ingredient.getType() == recipeMaterial) diff --git a/src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java b/src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java deleted file mode 100644 index 83e993a10..000000000 --- a/src/main/java/com/gmail/nossr50/util/skills/SmeltingTracker.java +++ /dev/null @@ -1,102 +0,0 @@ -package com.gmail.nossr50.util.skills; - -import com.gmail.nossr50.datatypes.player.McMMOPlayer; -import com.gmail.nossr50.datatypes.skills.PrimarySkillType; -import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.player.UserManager; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.block.Furnace; -import org.bukkit.entity.Player; -import org.bukkit.inventory.FurnaceInventory; -import org.bukkit.inventory.Inventory; -import org.jetbrains.annotations.Nullable; - -import java.util.UUID; - -public class SmeltingTracker { - -// private final HashMap furnaceOwners; - - private void changeFurnaceOwnership(Furnace furnace, Player player) { - - McMMOPlayer mcMMOPlayer = UserManager.getPlayer(player); - - /* - Debug output - */ - printOwnershipGainDebug(furnace, mcMMOPlayer); - - printOwnershipLossDebug(furnace); - - setFurnaceOwner(furnace, player); - } - - private void setFurnaceOwner(Furnace furnace, Player player) { - mcMMO.getMetadataService().getBlockMetadataService().setFurnaceOwner(furnace, player.getUniqueId()); - } - - private void printOwnershipGainDebug(Furnace furnace, McMMOPlayer mcMMOPlayer) { - if(mcMMOPlayer != null) { - if(mcMMOPlayer.isDebugMode()) { - mcMMOPlayer.getPlayer().sendMessage("Furnace ownership " + - ChatColor.GREEN +"gained " + ChatColor.RESET + - "at location: " + furnace.getLocation().toString()); - } - - } - } - - private void printOwnershipLossDebug(Furnace furnace) { - OfflinePlayer furnaceOwner = getFurnaceOwner(furnace); - - if(furnaceOwner != null && furnaceOwner.isOnline()) { - McMMOPlayer furnaceOwnerProfile = UserManager.getPlayer(furnaceOwner.getPlayer()); - - if(furnaceOwnerProfile != null) { - if(furnaceOwnerProfile.isDebugMode()) { - furnaceOwnerProfile.getPlayer().sendMessage("Furnace ownership " + - ChatColor.RED + "lost " + ChatColor.RESET + - "at location: " + furnace.getLocation().toString()); - } - } - } - } - - public @Nullable OfflinePlayer getFurnaceOwner(Furnace furnace) { - UUID uuid = mcMMO.getMetadataService().getBlockMetadataService().getFurnaceOwner(furnace); - - if(uuid != null) { - return Bukkit.getOfflinePlayer(uuid); - } else { - return null; - } - } - - @Nullable - public Furnace getFurnaceFromInventory(Inventory inventory) { - if (!(inventory instanceof FurnaceInventory)) { - return null; - } - - return (Furnace) inventory.getHolder(); - } - - public boolean isFurnaceOwned(Furnace furnace) { - return getFurnaceOwner(furnace) != null; - } - - public void processFurnaceOwnership(Furnace furnace, Player player) { - if(!mcMMO.p.getSkillTools().doesPlayerHaveSkillPermission(player, PrimarySkillType.SMELTING)) - return; - - //Don't swap ownership if its the same player - if(getFurnaceOwner(furnace) != null) { - if(getFurnaceOwner(furnace).getUniqueId().equals(player.getUniqueId())) - return; - } - - changeFurnaceOwnership(furnace, player); - } -} diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java index e3b21da03..c809444fa 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundManager.java @@ -13,34 +13,30 @@ public class SoundManager { * Sends a sound to the player * @param soundType the type of sound */ - public static void sendSound(Player player, Location location, SoundType soundType) - { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + public static void sendSound(Player player, Location location, SoundType soundType) { + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), SoundCategory.MASTER, getVolume(soundType), getPitch(soundType)); } - public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) - { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory) { + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), getPitch(soundType)); } - public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory, float pitchModifier) - { + public static void sendCategorizedSound(Player player, Location location, SoundType soundType, SoundCategory soundCategory, float pitchModifier) { float totalPitch = Math.min(2.0F, (getPitch(soundType) + pitchModifier)); - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) player.playSound(location, getSound(soundType), soundCategory, getVolume(soundType), totalPitch); } - public static void worldSendSound(World world, Location location, SoundType soundType) - { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + public static void worldSendSound(World world, Location location, SoundType soundType) { + if (SoundConfig.getInstance().getIsEnabled(soundType)) world.playSound(location, getSound(soundType), getVolume(soundType), getPitch(soundType)); } public static void worldSendSoundMaxPitch(World world, Location location, SoundType soundType) { - if(SoundConfig.getInstance().getIsEnabled(soundType)) + if (SoundConfig.getInstance().getIsEnabled(soundType)) world.playSound(location, getSound(soundType), getVolume(soundType), 2.0F); } @@ -49,14 +45,12 @@ public class SoundManager { * @param soundType target soundtype * @return the volume for this soundtype */ - private static float getVolume(SoundType soundType) - { + private static float getVolume(SoundType soundType) { return SoundConfig.getInstance().getVolume(soundType) * SoundConfig.getInstance().getMasterVolume(); } - private static float getPitch(SoundType soundType) - { - if(soundType == SoundType.FIZZ) + private static float getPitch(SoundType soundType) { + if (soundType == SoundType.FIZZ) return getFizzPitch(); else if (soundType == SoundType.POP) return getPopPitch(); @@ -64,8 +58,7 @@ public class SoundManager { return SoundConfig.getInstance().getPitch(soundType); } - private static Sound getSound(SoundType soundType) - { + private static Sound getSound(SoundType soundType) { return switch (soundType) { case ANVIL -> Sound.BLOCK_ANVIL_PLACE; case ITEM_BREAK -> Sound.ENTITY_ITEM_BREAK; diff --git a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java index 67e9b0e0b..5b4a083f3 100644 --- a/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java +++ b/src/main/java/com/gmail/nossr50/util/sounds/SoundType.java @@ -18,8 +18,7 @@ public enum SoundType { ITEM_CONSUMED, TIRED; - public boolean usesCustomPitch() - { + public boolean usesCustomPitch() { switch(this){ case POP: case FIZZ: diff --git a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java index d0252a846..b906058fa 100644 --- a/src/main/java/com/gmail/nossr50/util/text/StringUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/StringUtils.java @@ -71,7 +71,7 @@ public class StringUtils { StringBuilder trimMessage = new StringBuilder(); for (int i = index; i < args.length; i++) { - if(i + 1 >= args.length) + if (i + 1 >= args.length) trimMessage.append(args[i]); else trimMessage.append(args[i]).append(" "); @@ -186,4 +186,9 @@ public class StringUtils { } } + public static String convertKeyToName(@NotNull String key) { + // used when no display name is given for a potion + final String noUnderscores = key.replace("_", " ").toLowerCase(Locale.ENGLISH); + return org.codehaus.plexus.util.StringUtils.capitalise(noUnderscores); + } } diff --git a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java index 89981bb85..2cbfe4b1a 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextComponentFactory.java @@ -10,6 +10,7 @@ import com.gmail.nossr50.listeners.InteractionManager; import com.gmail.nossr50.locale.LocaleLoader; import com.gmail.nossr50.mcMMO; import com.gmail.nossr50.util.Permissions; +import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.text.Component; @@ -345,7 +346,8 @@ public class TextComponentFactory { componentBuilder.append(Component.newline()); //Finally, add details to the tooltip - abstractSubSkill.addStats(componentBuilder, player); + // TODO: pass in McMMOPlayer instead + abstractSubSkill.addStats(componentBuilder, UserManager.getPlayer(player)); } return componentBuilder.build(); diff --git a/src/main/java/com/gmail/nossr50/util/text/TextUtils.java b/src/main/java/com/gmail/nossr50/util/text/TextUtils.java index 1d3c001d5..782bd5ccc 100644 --- a/src/main/java/com/gmail/nossr50/util/text/TextUtils.java +++ b/src/main/java/com/gmail/nossr50/util/text/TextUtils.java @@ -31,15 +31,15 @@ public class TextUtils { TextComponent.Builder componentBuilder = Component.text(); for(Component component : componentsArray) { - if(component == null) //Individual elements can be null + if (component == null) //Individual elements can be null continue; - if(prefixComponent != null) + if (prefixComponent != null) componentBuilder.append(prefixComponent); componentBuilder.append(component); - if(suffixComponent != null) + if (suffixComponent != null) componentBuilder.append(suffixComponent); } @@ -68,14 +68,14 @@ public class TextUtils { int indexOfPotentialMember = i + (groupsFinished * 3); //Groups don't always fill all members neatly //Some groups won't have entirely non-null elements - if(indexOfPotentialMember > components.size()-1) { + if (indexOfPotentialMember > components.size()-1) { break; } Component potentialMember = components.get(indexOfPotentialMember); //Make sure the potential member exists because of rounding - if(potentialMember != null) { + if (potentialMember != null) { splitGroups[groupsFinished][i] = potentialMember; } } @@ -113,7 +113,7 @@ public class TextUtils { } public static @NotNull TextComponent colorizeText(@NotNull String rawtext) { - if(customLegacySerializer == null) { + if (customLegacySerializer == null) { customLegacySerializer = getSerializer(); } @@ -139,7 +139,7 @@ public class TextUtils { } public static @NotNull String sanitizeForSerializer(@NotNull String string) { - if(customLegacySerializer == null) { + if (customLegacySerializer == null) { customLegacySerializer = getSerializer(); } diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java index 29b4e89c2..f3ccd14ec 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardManager.java @@ -19,15 +19,14 @@ public class WorldGuardManager { private WorldGuardPlugin worldGuardPluginRef; public static WorldGuardManager getInstance() { - if(instance == null) + if (instance == null) instance = new WorldGuardManager(); return instance; } - public boolean hasMainFlag(Player player) - { - if(player == null) + public boolean hasMainFlag(Player player) { + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -41,9 +40,8 @@ public class WorldGuardManager { return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_ENABLE_WG_FLAG); } - public boolean hasXPFlag(Player player) - { - if(player == null) + public boolean hasXPFlag(Player player) { + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -57,9 +55,8 @@ public class WorldGuardManager { return query.testState(loc, WorldGuardPlugin.inst().wrapPlayer(player), WorldGuardFlags.MCMMO_XP_WG_FLAG); } - public boolean hasHardcoreFlag(Player player) - { - if(player == null) + public boolean hasHardcoreFlag(Player player) { + if (player == null) return false; BukkitPlayer localPlayer = BukkitAdapter.adapt(player); @@ -85,8 +82,7 @@ public class WorldGuardManager { return worldGuardPluginRef; } - public void registerFlags() - { + public void registerFlags() { try { FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); diff --git a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java index d37f0a50c..9cc190b7d 100644 --- a/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java +++ b/src/main/java/com/gmail/nossr50/worldguard/WorldGuardUtils.java @@ -41,9 +41,8 @@ public class WorldGuardUtils { WGClassList.add("com.sk89q.worldguard.protection.regions.RegionQuery"); } - public static boolean isWorldGuardLoaded() - { - if(detectedIncompatibleWG) + public static boolean isWorldGuardLoaded() { + if (detectedIncompatibleWG) return false; worldGuardPluginRef = getWorldGuard(); @@ -56,25 +55,22 @@ public class WorldGuardUtils { * Results are cached * @return the instance of WG plugin, null if its not compatible or isn't present */ - private static WorldGuardPlugin getWorldGuard() - { + private static WorldGuardPlugin getWorldGuard() { //WG plugin reference is already cached so just return it - if(isLoaded) + if (isLoaded) return worldGuardPluginRef; //Grab WG if it exists Plugin plugin = getServer().getPluginManager().getPlugin("WorldGuard"); - if(plugin == null) { + if (plugin == null) { //WG is not present detectedIncompatibleWG = true; LogUtils.debug(mcMMO.p.getLogger(), "WorldGuard was not detected."); } else { //Check that its actually of class WorldGuardPlugin - if(plugin instanceof WorldGuardPlugin) - { - if(isCompatibleVersion(plugin)) - { + if (plugin instanceof WorldGuardPlugin) { + if (isCompatibleVersion(plugin)) { worldGuardPluginRef = (WorldGuardPlugin) plugin; isLoaded = true; } @@ -119,8 +115,8 @@ public class WorldGuardUtils { * If WG appears to have all of its classes we can then check to see if its been initialized properly */ try { - if(allClassesFound) { - if(!((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).isInitialized()) { + if (allClassesFound) { + if (!((SimpleFlagRegistry) WorldGuard.getInstance().getFlagRegistry()).isInitialized()) { markWGIncompatible(); mcMMO.p.getLogger().severe("WG did not initialize properly, this can cause errors with mcMMO so mcMMO is disabling certain features."); } diff --git a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java index 4ce8fee08..4c4879610 100644 --- a/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java +++ b/src/main/java/net/shatteredlands/shatt/backup/ZipLibrary.java @@ -73,8 +73,7 @@ public class ZipLibrary { for (File source : sources) { if (source.isDirectory()) { zipDir(zipOut, "", source); - } - else { + } else { zipFile(zipOut, "", source); } } @@ -104,8 +103,7 @@ public class ZipLibrary { for (File source : files) { if (source.isDirectory()) { zipDir(zos, path, source); - } - else { + } else { zipFile(zos, path, source); } } diff --git a/src/main/resources/experience.yml b/src/main/resources/experience.yml index a41609521..e010c8d65 100644 --- a/src/main/resources/experience.yml +++ b/src/main/resources/experience.yml @@ -1,13 +1,3 @@ -# -# Experience configuration -# Last updated on ${project.version}-b${BUILD_NUMBER} -# -# Configure the experience formula and experience settings here. -# -##### - - - # https://hub.spigotmc.org/javadocs/spigot/org/bukkit/boss/BarColor.html # These are the only valid colors for Experience Bars, use the exact name found here # BLUE, GREEN, PINK, PURPLE, RED, WHITE, YELLOW (As of the time of this update these are the only Bar colors available, this could change in the future so check the BarColor enum to see if it has) @@ -48,7 +38,7 @@ Fishing_ExploitFix_Options: MoveRange: 3 OverFishLimit: 10 Experience_Bars: - # Turn this to false if you wanna disable XP bars + # Turn this to false if you want to disable XP bars Enable: true Update: # XP that you gained from your party but not yourself @@ -98,6 +88,10 @@ Experience_Bars: Enable: true Color: YELLOW BarStyle: SEGMENTED_6 + Maces: + Enable: true + Color: BLUE + BarStyle: SEGMENTED_6 Repair: Enable: true Color: PURPLE @@ -170,6 +164,7 @@ Experience_Formula: # Experience gained will get multiplied by these values. 1.0 by default, 0.5 means half XP gained. This happens right before multiplying the XP by the global multiplier. Skill_Multiplier: + Maces: 1.0 Crossbows: 1.0 Tridents: 1.0 Swords: 1.0 @@ -217,6 +212,9 @@ Diminished_Returns: Repair: 20000 Fishing: 20000 Alchemy: 20000 + Crossbows: 20000 + Tridents: 20000 + Maces: 20000 Time_Interval: 10 @@ -241,17 +239,18 @@ Experience_Values: # FeatherFall_Multiplier: Multiply Acrobatics XP by this value when wearing boots with the Feather Fall enchant FeatherFall_Multiplier: 2.0 Alchemy: - # Alchemy potion stages are based on the number of ingredients added - # Potion_Stage_1 represents a base potion - # Potion_Stage_2 represents a base potion with one ingredient - # Potion_Stage_3 represents a base potion with one ingredient and one amplifier - # Potion_Stage_4 represents a base potion with one ingredient and two amplifiers - # Potion_Stage_5 represents a base potion with one ingredient where the amplifiers are swapped - Potion_Stage_1: 15 - Potion_Stage_2: 30 - Potion_Stage_3: 60 - Potion_Stage_4: 120 - Potion_Stage_5: 0 + Potion_Brewing: + # Alchemy potion stages are based on the number of ingredients added + # Stage_1 represents a base potion + # Stage_2 represents a base potion with one ingredient + # Stage_3 represents a base potion with one ingredient and one amplifier + # Stage_4 represents a base potion with one ingredient and two amplifiers + # Stage_5 represents a base potion with one ingredient where the amplifiers are swapped + Stage_1: 666 + Stage_2: 1111 + Stage_3: 1750 + Stage_4: 2250 + Stage_5: 0 Archery: Distance_Multiplier: 0.025 Fishing: @@ -582,6 +581,7 @@ Experience_Values: Combat: Multiplier: Animals: 1.0 + Armadillo: 1.1 Creeper: 4.0 Skeleton: 3.0 Spider: 2.0 diff --git a/src/main/resources/locale/locale_en_US.properties b/src/main/resources/locale/locale_en_US.properties index 11e550b20..f2fcc7a26 100644 --- a/src/main/resources/locale/locale_en_US.properties +++ b/src/main/resources/locale/locale_en_US.properties @@ -1,3 +1,4 @@ +Placeholder= This value is for any WIP locale entries that will not be displayed to users JSON.Rank=Rank JSON.DescriptionHeader=Description: JSON.JWrapper.Header=Details @@ -26,6 +27,7 @@ JSON.Salvage=Salvage JSON.Swords=Swords JSON.Taming=Taming JSON.Tridents=Tridents +JSON.Maces=Maces JSON.Unarmed=Unarmed JSON.Woodcutting=Woodcutting JSON.URL.Website=The official mcMMO Website! @@ -96,6 +98,7 @@ Overhaul.Name.Smelting=Smelting Overhaul.Name.Swords=Swords Overhaul.Name.Taming=Taming Overhaul.Name.Tridents=Tridents +Overhaul.Name.Maces=Maces Overhaul.Name.Unarmed=Unarmed Overhaul.Name.Woodcutting=Woodcutting # /mcMMO Command Style Stuff @@ -122,6 +125,7 @@ XPBar.Smelting=Smelting Lv.&6{0} XPBar.Swords=Swords Lv.&6{0} XPBar.Taming=Taming Lv.&6{0} XPBar.Tridents=Tridents Lv.&6{0} +XPBar.Maces=Maces Lv.&6{0} XPBar.Unarmed=Unarmed Lv.&6{0} XPBar.Woodcutting=Woodcutting Lv.&6{0} #This is just a preset template that gets used if the 'ExtraDetails' setting is turned on in experience.yml (off by default), you can ignore this template and just edit the strings above @@ -457,9 +461,6 @@ Tridents.Listener=Tridents: Maces.SkillName=MACES Maces.Ability.Lower=&7You lower your mace. Maces.Ability.Ready=&3You &6ready&3 your Mace. -Maces.Skills.MaceSmash.Refresh=&aYour &eGiga Smash &aability is refreshed! -Maces.Skills.MaceSmash.Other.On=&a{0}&2 used &cGiga Smash! -Maces.SubSkill.GigaSmash.Name=Giga Smash Maces.SubSkill.MacesLimitBreak.Name=Maces Limit Break Maces.SubSkill.MacesLimitBreak.Description=Breaking your limits. Increased damage against tough opponents. Intended for PVP, up to server settings for whether it will boost damage in PVE. Maces.SubSkill.MacesLimitBreak.Stat=Limit Break Max DMG diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 198d465fc..52500d4cb 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -14,7 +14,7 @@ author: nossr50 authors: [GJ, NuclearW, bm01, Glitchfinder, TfT_02, t00thpick1, Riking, electronicboy, kashike] website: https://www.mcmmo.org main: com.gmail.nossr50.mcMMO -softdepend: [WorldGuard, CombatTag, HealthBar, PlaceholderAPI] +softdepend: [WorldGuard, CombatTag, HealthBar, PlaceholderAPI, ProtocolLib] load: POSTWORLD folia-supported: true api-version: 1.13 @@ -154,6 +154,9 @@ commands: salvage: description: Detailed mcMMO skill info permission: mcmmo.commands.salvage + maces: + description: Detailed mcMMO skill info + permission: mcmmo.commands.maces mmopower: description: Shows skill mastery and power level info permission: mcmmo.commands.mmopower diff --git a/src/main/resources/skillranks.yml b/src/main/resources/skillranks.yml index 590ddde11..e6cea3643 100644 --- a/src/main/resources/skillranks.yml +++ b/src/main/resources/skillranks.yml @@ -443,6 +443,29 @@ Salvage: Rank_6: 750 Rank_7: 850 Rank_8: 1000 +Maces: + Standard: + Rank_1: 10 + Rank_2: 20 + Rank_3: 30 + Rank_4: 40 + Rank_5: 50 + Rank_6: 60 + Rank_7: 70 + Rank_8: 80 + Rank_9: 90 + Rank_10: 100 + RetroMode: + Rank_1: 100 + Rank_2: 200 + Rank_3: 300 + Rank_4: 400 + Rank_5: 500 + Rank_6: 600 + Rank_7: 700 + Rank_8: 800 + Rank_9: 900 + Rank_10: 1000 Mining: MotherLode: Standard: diff --git a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java index d995ed569..984c5f123 100644 --- a/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java +++ b/src/test/java/com/gmail/nossr50/MMOTestEnvironment.java @@ -16,11 +16,9 @@ import com.gmail.nossr50.util.blockmeta.ChunkManager; import com.gmail.nossr50.util.player.UserManager; import com.gmail.nossr50.util.skills.RankUtils; import com.gmail.nossr50.util.skills.SkillTools; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Server; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemFactory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.PluginManager; @@ -31,9 +29,10 @@ import java.util.UUID; import java.util.logging.Logger; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; public abstract class MMOTestEnvironment { + protected MockedStatic mockedBukkit; protected MockedStatic mockedMcMMO; protected MockedStatic mockedChatConfig; protected MockedStatic experienceConfig; @@ -63,26 +62,27 @@ public abstract class MMOTestEnvironment { protected PlayerProfile playerProfile; protected McMMOPlayer mmoPlayer; protected String playerName = "testPlayer"; + protected ItemFactory itemFactory; protected ChunkManager chunkManager; protected MaterialMapStore materialMapStore; protected void mockBaseEnvironment(Logger logger) throws InvalidSkillException { - mockedMcMMO = Mockito.mockStatic(mcMMO.class); - mcMMO.p = Mockito.mock(mcMMO.class); + mockedMcMMO = mockStatic(mcMMO.class); + mcMMO.p = mock(mcMMO.class); when(mcMMO.p.getLogger()).thenReturn(logger); // place store - chunkManager = Mockito.mock(ChunkManager.class); - when(mcMMO.getPlaceStore()).thenReturn(chunkManager); + chunkManager = mock(ChunkManager.class); + when(mcMMO.getUserBlockTracker()).thenReturn(chunkManager); // shut off mod manager for woodcutting - when(mcMMO.getModManager()).thenReturn(Mockito.mock(ModManager.class)); + when(mcMMO.getModManager()).thenReturn(mock(ModManager.class)); when(mcMMO.getModManager().isCustomLog(any())).thenReturn(false); // chat config - mockedChatConfig = Mockito.mockStatic(ChatConfig.class); - when(ChatConfig.getInstance()).thenReturn(Mockito.mock(ChatConfig.class)); + mockedChatConfig = mockStatic(ChatConfig.class); + when(ChatConfig.getInstance()).thenReturn(mock(ChatConfig.class)); // general config mockGeneralConfig(); @@ -108,29 +108,34 @@ public abstract class MMOTestEnvironment { mockPermissions(); - mockedRankUtils = Mockito.mockStatic(RankUtils.class); + mockedRankUtils = mockStatic(RankUtils.class); // wire server - this.server = Mockito.mock(Server.class); + this.server = mock(Server.class); when(mcMMO.p.getServer()).thenReturn(server); + mockedBukkit = mockStatic(Bukkit.class); + when(Bukkit.getItemFactory()).thenReturn(itemFactory); + itemFactory = mock(ItemFactory.class); + // when(itemFactory.getItemMeta(any())).thenReturn(mock(ItemMeta.class)); + // wire plugin manager - this.pluginManager = Mockito.mock(PluginManager.class); + this.pluginManager = mock(PluginManager.class); when(server.getPluginManager()).thenReturn(pluginManager); // wire world - this.world = Mockito.mock(World.class); + this.world = mock(World.class); // wire Misc - this.mockedMisc = Mockito.mockStatic(Misc.class); + this.mockedMisc = mockStatic(Misc.class); when(Misc.getBlockCenter(any())).thenReturn(new Location(world, 0, 0, 0)); // setup player and player related mocks after everything else - this.player = Mockito.mock(Player.class); + this.player = mock(Player.class); when(player.getUniqueId()).thenReturn(playerUUID); // wire inventory - this.playerInventory = Mockito.mock(PlayerInventory.class); + this.playerInventory = mock(PlayerInventory.class); when(player.getInventory()).thenReturn(playerInventory); // PlayerProfile and McMMOPlayer are partially mocked @@ -138,7 +143,7 @@ public abstract class MMOTestEnvironment { mmoPlayer = Mockito.spy(new McMMOPlayer(player, playerProfile)); // wire user manager - this.mockedUserManager = Mockito.mockStatic(UserManager.class); + this.mockedUserManager = mockStatic(UserManager.class); when(UserManager.getPlayer(player)).thenReturn(mmoPlayer); this.materialMapStore = new MaterialMapStore(); @@ -146,7 +151,7 @@ public abstract class MMOTestEnvironment { } private void mockPermissions() { - mockedPermissions = Mockito.mockStatic(Permissions.class); + mockedPermissions = mockStatic(Permissions.class); when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(true); when(Permissions.canUseSubSkill(any(Player.class), any(SubSkillType.class))).thenReturn(true); when(Permissions.isSubSkillEnabled(any(Player.class), any(SubSkillType.class))).thenReturn(true); @@ -155,16 +160,16 @@ public abstract class MMOTestEnvironment { } private void mockRankConfig() { - rankConfig = Mockito.mock(RankConfig.class); + rankConfig = mock(RankConfig.class); } private void mockAdvancedConfig() { - this.advancedConfig = Mockito.mock(AdvancedConfig.class); + this.advancedConfig = mock(AdvancedConfig.class); when(mcMMO.p.getAdvancedConfig()).thenReturn(advancedConfig); } private void mockGeneralConfig() { - generalConfig = Mockito.mock(GeneralConfig.class); + generalConfig = mock(GeneralConfig.class); when(generalConfig.getTreeFellerThreshold()).thenReturn(100); when(generalConfig.getDoubleDropsEnabled(PrimarySkillType.WOODCUTTING, Material.OAK_LOG)).thenReturn(true); when(generalConfig.getLocale()).thenReturn("en_US"); @@ -172,15 +177,15 @@ public abstract class MMOTestEnvironment { } private void mockPartyConfig() { - partyConfig = Mockito.mock(PartyConfig.class); + partyConfig = mock(PartyConfig.class); when(partyConfig.isPartyEnabled()).thenReturn(false); when(mcMMO.p.getPartyConfig()).thenReturn(partyConfig); } private void mockExperienceConfig() { - experienceConfig = Mockito.mockStatic(ExperienceConfig.class); + experienceConfig = mockStatic(ExperienceConfig.class); - when(ExperienceConfig.getInstance()).thenReturn(Mockito.mock(ExperienceConfig.class)); + when(ExperienceConfig.getInstance()).thenReturn(mock(ExperienceConfig.class)); // Combat when(ExperienceConfig.getInstance().getCombatXP("Cow")).thenReturn(1D); @@ -212,5 +217,8 @@ public abstract class MMOTestEnvironment { if (mockedEventUtils != null) { mockedEventUtils.close(); } + if (mockedBukkit != null) { + mockedBukkit.close(); + } } } diff --git a/src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java b/src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java new file mode 100644 index 000000000..b9b648046 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/config/skills/alchemy/PotionConfigTest.java @@ -0,0 +1,69 @@ +//package com.gmail.nossr50.config.skills.alchemy; +// +//import com.gmail.nossr50.MMOTestEnvironment; +//import org.bukkit.inventory.meta.ItemMeta; +//import org.bukkit.inventory.meta.PotionMeta; +//import org.junit.jupiter.api.AfterEach; +//import org.junit.jupiter.api.BeforeEach; +//import org.junit.jupiter.api.Test; +// +//import java.io.File; +//import java.net.URL; +//import java.util.logging.Logger; +// +//import static org.junit.jupiter.api.Assertions.assertNotNull; +//import static org.mockito.ArgumentMatchers.any; +//import static org.mockito.Mockito.mock; +//import static org.mockito.Mockito.when; +// +//class PotionConfigTest extends MMOTestEnvironment { +// +// public static final String POTION_LEGACY_POTION_YML = "potion/legacy_potion.yml"; +// public static final String POTION_MODERN_YML = "potion/modern_potion.yml"; +// public static final Logger logger = Logger.getLogger(PotionConfigTest.class.getName()); +// +// @BeforeEach +// void setUp() { +// mockBaseEnvironment(logger); +// final PotionMeta potionMeta = mock(PotionMeta.class); +// when(itemFactory.getItemMeta(any())).thenReturn(potionMeta); +// } +// +// @AfterEach +// void tearDown() { +// cleanupBaseEnvironment(); +// } +// +// @Test +// void testLoadLegacyConfig() { +// final PotionConfig potionConfig = getPotionConfig(POTION_LEGACY_POTION_YML); +// assertNotNull(potionConfig); +// +// potionConfig.loadConcoctions(); +// int loaded = potionConfig.loadPotionMap(); +// System.out.println("Loaded " + loaded + " potions"); +// } +// +// @Test +// void testModernConfig() { +// final PotionConfig potionConfig = getPotionConfig(POTION_MODERN_YML); +// assertNotNull(potionConfig); +// +// potionConfig.loadConcoctions(); +// int loaded = potionConfig.loadPotionMap(); +// System.out.println("Loaded " + loaded + " potions"); +// } +// +// private PotionConfig getPotionConfig(String path) { +// // Get the file URL using the class loader +// final URL resource = getClass().getClassLoader().getResource(path); +// if (resource == null) { +// throw new IllegalArgumentException("file not found!"); +// } else { +// // Convert URL to a File object +// final File potionFile = new File(resource.getFile()); +// System.out.println("File path: " + potionFile.getAbsolutePath()); +// return new PotionConfig(potionFile); +// } +// } +//} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java index 23463cbdb..c0c448bc7 100644 --- a/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java +++ b/src/test/java/com/gmail/nossr50/database/FlatFileDatabaseManagerTest.java @@ -10,7 +10,6 @@ import com.gmail.nossr50.util.skills.SkillTools; import com.google.common.io.Files; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -38,32 +37,30 @@ class FlatFileDatabaseManagerTest { public static final @NotNull String BAD_DATA_FILE_LINE_TWENTY_THREE = "nossr51:baddata:::baddata:baddata:640:baddata:1000:1000:1000:baddata:baddata:baddata:baddata:16:0:500:20273:0:0:0:0::1000:0:0:baddata:1593543012:0:0:0:0::1000:0:0:baddata:IGNORED:1000:0:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1:0:"; public static final @NotNull String DB_BADDATA = "baddatadb.users"; public static final @NotNull String DB_HEALTHY = "healthydb.users"; - public static final @NotNull String HEALTHY_DB_LINE_1 = "nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:IGNORED:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:2020:140:14:150:15:1111:2222:3333"; public static final @NotNull String HEALTHY_DB_LINE_ONE_UUID_STR = "588fe472-1c82-4c4e-9aa1-7eefccb277e3"; public static final String DB_MISSING_LAST_LOGIN = "missinglastlogin.users"; - public static final String LINE_TWO_FROM_MISSING_DB = "nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:0:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:"; private static File tempDir; private final static @NotNull Logger logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); private final long PURGE_TIME = 2630000000L; - private static @Nullable FlatFileDatabaseManager db; //Making them all unique makes it easier on us to edit this stuff later int expectedLvlMining = 1, expectedLvlWoodcutting = 2, expectedLvlRepair = 3, expectedLvlUnarmed = 4, expectedLvlHerbalism = 5, expectedLvlExcavation = 6, expectedLvlArchery = 7, expectedLvlSwords = 8, expectedLvlAxes = 9, expectedLvlAcrobatics = 10, expectedLvlTaming = 11, expectedLvlFishing = 12, expectedLvlAlchemy = 13, expectedLvlCrossbows = 14, - expectedLvlTridents = 15; + expectedLvlTridents = 15, expectedLvlMaces = 16; float expectedExpMining = 10, expectedExpWoodcutting = 20, expectedExpRepair = 30, expectedExpUnarmed = 40, expectedExpHerbalism = 50, expectedExpExcavation = 60, expectedExpArchery = 70, expectedExpSwords = 80, expectedExpAxes = 90, expectedExpAcrobatics = 100, expectedExpTaming = 110, expectedExpFishing = 120, expectedExpAlchemy = 130, expectedExpCrossbows = 140, - expectedExpTridents = 150; + expectedExpTridents = 150, expectedExpMaces = 160; long expectedBerserkCd = 111, expectedGigaDrillBreakerCd = 222, expectedTreeFellerCd = 333, expectedGreenTerraCd = 444, expectedSerratedStrikesCd = 555, expectedSkullSplitterCd = 666, expectedSuperBreakerCd = 777, expectedBlastMiningCd = 888, expectedChimaeraWingCd = 999, - expectedSuperShotgunCd = 1111, expectedTridentSuperCd = 2222, expectedExplosiveShotCd = 3333; + expectedSuperShotgunCd = 1111, expectedTridentSuperCd = 2222, expectedExplosiveShotCd = 3333, + expectedMacesSuperCd = 4444; int expectedScoreboardTips = 1111; Long expectedLastLogin = 2020L; @@ -75,10 +72,8 @@ class FlatFileDatabaseManagerTest { @BeforeEach void init() { - assertNull(db); //noinspection UnstableApiUsage tempDir = Files.createTempDir(); - db = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); } private @NotNull String getTemporaryUserFilePath() { @@ -88,7 +83,6 @@ class FlatFileDatabaseManagerTest { @AfterEach void tearDown() { recursiveDelete(tempDir); - db = null; } //Nothing wrong with this database @@ -150,17 +144,19 @@ class FlatFileDatabaseManagerTest { @Test void testDefaultInit() { - db = new FlatFileDatabaseManager(getTemporaryUserFilePath(), logger, PURGE_TIME, 0); + new FlatFileDatabaseManager(getTemporaryUserFilePath(), logger, PURGE_TIME, 0); } @Test void testUpdateLeaderboards() { - assertNotNull(db); - assertEquals(LeaderboardStatus.UPDATED, db.updateLeaderboards()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + assertNotNull(flatFileDatabaseManager); + assertEquals(LeaderboardStatus.UPDATED, flatFileDatabaseManager.updateLeaderboards()); } @Test void testSaveUser() { + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); //Make a Profile to save and check to see if it worked UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); String playerName = "nossr50"; @@ -168,15 +164,15 @@ class FlatFileDatabaseManagerTest { //The above profile should be "zero" initialized //Save the zero version and see if it looks correct - assertNotNull(db); - assertTrue(db.getUsersFile().exists()); //Users file should have been created from the above com.gmail.nossr50.database.FlatFileDatabaseManager.checkFileHealthAndStructure - assertNotNull(db.getUsersFile()); + assertNotNull(flatFileDatabaseManager); + assertTrue(flatFileDatabaseManager.getUsersFile().exists()); //Users file should have been created from the above com.gmail.nossr50.database.FlatFileDatabaseManager.checkFileHealthAndStructure + assertNotNull(flatFileDatabaseManager.getUsersFile()); - //The DB is empty at this point, add our user - assertTrue(db.saveUser(testProfile)); //True means we saved the user + //The flatFileDatabaseManager is empty at this point, add our user + assertTrue(flatFileDatabaseManager.saveUser(testProfile)); //True means we saved the user //Check for the empty profile - PlayerProfile retrievedFromData = db.loadPlayerProfile(uuid); + PlayerProfile retrievedFromData = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, retrievedFromData.getUniqueId()); assertEquals(playerName, retrievedFromData.getPlayerName()); @@ -187,9 +183,9 @@ class FlatFileDatabaseManagerTest { String alteredName = "changedmyname"; PlayerProfile changedNameProfile = new PlayerProfile(alteredName, uuid, 0); - assertTrue(db.saveUser(changedNameProfile)); //True means we saved the user + assertTrue(flatFileDatabaseManager.saveUser(changedNameProfile)); //True means we saved the user - retrievedFromData = db.loadPlayerProfile(uuid); + retrievedFromData = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns true if the data was created from the file, false if it wasn't found and a dummy profile was returned assertEquals(uuid, retrievedFromData.getUniqueId()); assertEquals(alteredName, retrievedFromData.getPlayerName()); @@ -198,49 +194,27 @@ class FlatFileDatabaseManagerTest { @Test void testAddedMissingLastLoginValues() { File dbFile = prepareDatabaseTestResource(DB_MISSING_LAST_LOGIN); - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(dbFile); - logger.info("File Path: "+ dbFile.getAbsolutePath()); - assertArrayEquals(LINE_TWO_FROM_MISSING_DB.split(":"), dataFromFile.get(1)); - assertEquals(dataFromFile.get(1)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNotNull(flagsFound); assertTrue(flagsFound.contains(FlatFileDataFlag.LAST_LOGIN_SCHEMA_UPGRADE)); //Check for the fixed value - PlayerProfile profile = db.loadPlayerProfile("nossr50"); + PlayerProfile profile = flatFileDatabaseManager.loadPlayerProfile("nossr50"); assertEquals(-1, (long) profile.getLastLogin()); } @Test void testLoadByName() { File healthyDB = prepareDatabaseTestResource(DB_HEALTHY); - - /* - * We have established the files are in good order, so now for the actual testing - */ - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(healthyDB); - logger.info("File Path: "+healthyDB.getAbsolutePath()); - assertArrayEquals(HEALTHY_DB_LINE_1.split(":"), dataFromFile.get(0)); - assertEquals(dataFromFile.get(0)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(healthyDB, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(healthyDB, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found - /* - * Once the DB looks fine load the profile - */ - String playerName = "nossr50"; UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); - PlayerProfile profile = db.loadPlayerProfile(playerName); + PlayerProfile profile = flatFileDatabaseManager.loadPlayerProfile(playerName); testHealthyDataProfileValues(playerName, uuid, profile); } @@ -251,16 +225,16 @@ class FlatFileDatabaseManagerTest { String playerName = "nossr50"; int newUserTestStartingLvl = 1337; - db = new FlatFileDatabaseManager(new File(tempDir.getPath() + File.separator + TEST_FILE_NAME), logger, PURGE_TIME, newUserTestStartingLvl, true); - db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(new File(tempDir.getPath() + File.separator + TEST_FILE_NAME), logger, PURGE_TIME, newUserTestStartingLvl, true); + flatFileDatabaseManager.checkFileHealthAndStructure(); - PlayerProfile playerProfile = db.newUser(playerName, uuid); + PlayerProfile playerProfile = flatFileDatabaseManager.newUser(playerName, uuid); assertTrue(playerProfile.isLoaded()); assertEquals(playerName, playerProfile.getPlayerName()); assertEquals(uuid, playerProfile.getUniqueId()); - PlayerProfile retrievedFromDisk = db.loadPlayerProfile(uuid); + PlayerProfile retrievedFromDisk = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromDisk.isLoaded()); assertEquals(playerName, retrievedFromDisk.getPlayerName()); assertEquals(uuid, retrievedFromDisk.getUniqueId()); @@ -270,11 +244,11 @@ class FlatFileDatabaseManagerTest { checkNewUserValues(retrievedFromDisk, newUserTestStartingLvl); //TODO: Should we do any dupe checking? Probably not needed as it would be caught on the next load - db.newUser("disco", new UUID(3, 3)); - db.newUser("dingus", new UUID(3, 4)); - db.newUser("duped_dingus", new UUID(3, 4)); + flatFileDatabaseManager.newUser("disco", new UUID(3, 3)); + flatFileDatabaseManager.newUser("dingus", new UUID(3, 4)); + flatFileDatabaseManager.newUser("duped_dingus", new UUID(3, 4)); - assertEquals(5, getSplitDataFromFile(db.getUsersFile()).size()); + assertEquals(5, getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()).size()); } @Test @@ -286,16 +260,16 @@ class FlatFileDatabaseManagerTest { File file = prepareDatabaseTestResource(DB_HEALTHY); //Existing DB int newUserTestStartingLvl = 1337; - db = new FlatFileDatabaseManager(file, logger, PURGE_TIME, newUserTestStartingLvl, true); - db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(file, logger, PURGE_TIME, newUserTestStartingLvl, true); + flatFileDatabaseManager.checkFileHealthAndStructure(); - PlayerProfile playerProfile = db.newUser(playerName, uuid); + PlayerProfile playerProfile = flatFileDatabaseManager.newUser(playerName, uuid); assertTrue(playerProfile.isLoaded()); assertEquals(playerName, playerProfile.getPlayerName()); assertEquals(uuid, playerProfile.getUniqueId()); - PlayerProfile retrievedFromDisk = db.loadPlayerProfile(uuid); + PlayerProfile retrievedFromDisk = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(retrievedFromDisk.isLoaded()); assertEquals(playerName, retrievedFromDisk.getPlayerName()); assertEquals(uuid, retrievedFromDisk.getUniqueId()); @@ -305,21 +279,21 @@ class FlatFileDatabaseManagerTest { checkNewUserValues(retrievedFromDisk, newUserTestStartingLvl); //TODO: Should we do any dupe checking? Probably not needed as it would be caught on the next load - db.newUser("bidoof", new UUID(3, 3)); - db.newUser("derp", new UUID(3, 4)); - db.newUser("pizza", new UUID(3, 4)); + flatFileDatabaseManager.newUser("bidoof", new UUID(3, 3)); + flatFileDatabaseManager.newUser("derp", new UUID(3, 4)); + flatFileDatabaseManager.newUser("pizza", new UUID(3, 4)); - assertEquals(7, getSplitDataFromFile(db.getUsersFile()).size()); + assertEquals(7, getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()).size()); - //Now we *fix* the DB and there should be one less - db.checkFileHealthAndStructure(); - assertEquals(6, getSplitDataFromFile(db.getUsersFile()).size()); + //Now we *fix* the flatFileDatabaseManager and there should be one less + flatFileDatabaseManager.checkFileHealthAndStructure(); + assertEquals(6, getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()).size()); } private void checkNewUserValues(@NotNull PlayerProfile playerProfile, int startingLevel) { //Checking a new user for being zero initialized for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) + if (SkillTools.isChildSkill(primarySkillType)) continue; assertEquals(startingLevel, playerProfile.getSkillLevel(primarySkillType)); @@ -338,71 +312,45 @@ class FlatFileDatabaseManagerTest { @Test void testLoadByUUID() { File dbFile = prepareDatabaseTestResource(DB_HEALTHY); - - /* - * We have established the files are in good order, so now for the actual testing - */ - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(dbFile); - logger.info("File Path: " + dbFile.getAbsolutePath()); - assertArrayEquals(HEALTHY_DB_LINE_1.split(":"), dataFromFile.get(0)); - assertEquals(dataFromFile.get(0)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found /* - * Once the DB looks fine load the profile + * Once the flatFileDatabaseManager looks fine load the profile */ String playerName = "nossr50"; UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); - PlayerProfile profile1 = db.loadPlayerProfile(uuid); + PlayerProfile profile1 = flatFileDatabaseManager.loadPlayerProfile(uuid); testHealthyDataProfileValues(playerName, uuid, profile1); - assertFalse(db.loadPlayerProfile(new UUID(0, 1)).isLoaded()); //This profile should not exist and therefor will return unloaded + assertFalse(flatFileDatabaseManager.loadPlayerProfile(new UUID(0, 1)).isLoaded()); //This profile should not exist and therefor will return unloaded } @Test void testLoadByUUIDAndName() { File dbFile = prepareDatabaseTestResource(DB_HEALTHY); - - /* - * We have established the files are in good order, so now for the actual testing - */ - - //This makes sure our private method is working before the tests run afterwards - ArrayList dataFromFile = getSplitDataFromFile(dbFile); - logger.info("File Path: " + dbFile.getAbsolutePath()); - assertArrayEquals(HEALTHY_DB_LINE_1.split(":"), dataFromFile.get(0)); - assertEquals(dataFromFile.get(0)[FlatFileDatabaseManager.UUID_INDEX], HEALTHY_DB_LINE_ONE_UUID_STR); - - db = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); - List flagsFound = db.checkFileHealthAndStructure(); + var flatFileDatabaseManager = new FlatFileDatabaseManager(dbFile, logger, PURGE_TIME, 0, true); + List flagsFound = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNull(flagsFound); //No flags should be found - /* - * Once the DB looks fine load the profile - */ - String playerName = "nossr50"; UUID uuid = UUID.fromString("588fe472-1c82-4c4e-9aa1-7eefccb277e3"); Player player = initMockPlayer(playerName, uuid); - PlayerProfile profile1 = db.loadPlayerProfile(player); + PlayerProfile profile1 = flatFileDatabaseManager.loadPlayerProfile(player); testHealthyDataProfileValues(playerName, uuid, profile1); String updatedName = "updatedName"; Player updatedNamePlayer = initMockPlayer(updatedName, uuid); - PlayerProfile updatedNameProfile = db.loadPlayerProfile(updatedNamePlayer); + PlayerProfile updatedNameProfile = flatFileDatabaseManager.loadPlayerProfile(updatedNamePlayer); testHealthyDataProfileValues(updatedName, uuid, updatedNameProfile); Player shouldNotExist = initMockPlayer("doesntexist", new UUID(0, 1)); - PlayerProfile profile3 = db.loadPlayerProfile(shouldNotExist); + PlayerProfile profile3 = flatFileDatabaseManager.loadPlayerProfile(shouldNotExist); assertFalse(profile3.isLoaded()); } @@ -421,7 +369,7 @@ class FlatFileDatabaseManagerTest { assertNotNull(resourceFileURI); File copyOfFile = new File(tempDir.getPath() + File.separator + dbFileName); - if(copyOfFile.exists()) { + if (copyOfFile.exists()) { //noinspection ResultOfMethodCallIgnored copyOfFile.delete(); } @@ -449,7 +397,7 @@ class FlatFileDatabaseManagerTest { */ for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) + if (SkillTools.isChildSkill(primarySkillType)) continue; int expectedLevelHealthyDBEntryOne = getExpectedLevelHealthyDBEntryOne(primarySkillType); @@ -484,6 +432,7 @@ class FlatFileDatabaseManagerTest { case BLAST_MINING -> expectedBlastMiningCd; case TRIDENTS_SUPER_ABILITY -> expectedTridentSuperCd; case EXPLOSIVE_SHOT -> expectedExplosiveShotCd; + case MACES_SUPER_ABILITY -> expectedMacesSuperCd; default -> throw new RuntimeException("Values not defined for super ability please add " + "values for " + superAbilityType.toString() + " to the test"); }; @@ -491,165 +440,147 @@ class FlatFileDatabaseManagerTest { } private float getExpectedExperienceHealthyDBEntryOne(@NotNull PrimarySkillType primarySkillType) { - switch(primarySkillType) { - case ACROBATICS: - return expectedExpAcrobatics; - case ALCHEMY: - return expectedExpAlchemy; - case ARCHERY: - return expectedExpArchery; - case AXES: - return expectedExpAxes; - case CROSSBOWS: - return expectedExpCrossbows; - case EXCAVATION: - return expectedExpExcavation; - case FISHING: - return expectedExpFishing; - case HERBALISM: - return expectedExpHerbalism; - case MINING: - return expectedExpMining; - case REPAIR: - return expectedExpRepair; - case SALVAGE: - case SMELTING: - return 0; - case SWORDS: - return expectedExpSwords; - case TAMING: - return expectedExpTaming; - case TRIDENTS: - return expectedExpTridents; - case UNARMED: - return expectedExpUnarmed; - case WOODCUTTING: - return expectedExpWoodcutting; - } + return switch (primarySkillType) { + case ACROBATICS -> expectedExpAcrobatics; + case ALCHEMY -> expectedExpAlchemy; + case ARCHERY -> expectedExpArchery; + case AXES -> expectedExpAxes; + case CROSSBOWS -> expectedExpCrossbows; + case EXCAVATION -> expectedExpExcavation; + case FISHING -> expectedExpFishing; + case HERBALISM -> expectedExpHerbalism; + case MINING -> expectedExpMining; + case REPAIR -> expectedExpRepair; + case SALVAGE, SMELTING -> 0; + case SWORDS -> expectedExpSwords; + case TAMING -> expectedExpTaming; + case TRIDENTS -> expectedExpTridents; + case UNARMED -> expectedExpUnarmed; + case WOODCUTTING -> expectedExpWoodcutting; + case MACES -> expectedExpMaces; + default -> + throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); + }; - throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); } private int getExpectedLevelHealthyDBEntryOne(@NotNull PrimarySkillType primarySkillType) { - switch(primarySkillType) { - case ACROBATICS: - return expectedLvlAcrobatics; - case ALCHEMY: - return expectedLvlAlchemy; - case ARCHERY: - return expectedLvlArchery; - case AXES: - return expectedLvlAxes; - case CROSSBOWS: - return expectedLvlCrossbows; - case EXCAVATION: - return expectedLvlExcavation; - case FISHING: - return expectedLvlFishing; - case HERBALISM: - return expectedLvlHerbalism; - case MINING: - return expectedLvlMining; - case REPAIR: - return expectedLvlRepair; - case SALVAGE: - case SMELTING: - return 0; - case SWORDS: - return expectedLvlSwords; - case TAMING: - return expectedLvlTaming; - case TRIDENTS: - return expectedLvlTridents; - case UNARMED: - return expectedLvlUnarmed; - case WOODCUTTING: - return expectedLvlWoodcutting; - } + return switch (primarySkillType) { + case ACROBATICS -> expectedLvlAcrobatics; + case ALCHEMY -> expectedLvlAlchemy; + case ARCHERY -> expectedLvlArchery; + case AXES -> expectedLvlAxes; + case CROSSBOWS -> expectedLvlCrossbows; + case EXCAVATION -> expectedLvlExcavation; + case FISHING -> expectedLvlFishing; + case HERBALISM -> expectedLvlHerbalism; + case MINING -> expectedLvlMining; + case REPAIR -> expectedLvlRepair; + case SALVAGE, SMELTING -> 0; + case SWORDS -> expectedLvlSwords; + case TAMING -> expectedLvlTaming; + case TRIDENTS -> expectedLvlTridents; + case UNARMED -> expectedLvlUnarmed; + case WOODCUTTING -> expectedLvlWoodcutting; + case MACES -> expectedLvlMaces; + default -> + throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); + }; - throw new RuntimeException("Values for skill not defined, please add values for " + primarySkillType.toString() + " to the test"); } @Test void testOverwriteName() { - overwriteDataAndCheckForFlag(db, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); - ArrayList splitDataLines = getSplitDataFromFile(db.getUsersFile()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); + ArrayList splitDataLines = getSplitDataFromFile(flatFileDatabaseManager.getUsersFile()); assertNotEquals(splitDataLines.get(1)[0], splitDataLines.get(0)[0]); //Name comparison } @Test void testDataNotFound() { + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); //Save the zero version and see if it looks correct - assertNotNull(db); - assertTrue(db.getUsersFile().exists()); - assertNotNull(db.getUsersFile()); + assertNotNull(flatFileDatabaseManager); + assertTrue(flatFileDatabaseManager.getUsersFile().exists()); + assertNotNull(flatFileDatabaseManager.getUsersFile()); //Check for the "unloaded" profile - PlayerProfile retrievedFromData = db.loadPlayerProfile("nossr50"); + PlayerProfile retrievedFromData = flatFileDatabaseManager.loadPlayerProfile("nossr50"); assertFalse(retrievedFromData.isLoaded()); //PlayerProfile::isLoaded returns false if data doesn't exist for the user } @Test void testPurgePowerlessUsers() { - replaceDataInFile(db, normalDatabaseData); - int purgeCount = db.purgePowerlessUsers(); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + replaceDataInFile(flatFileDatabaseManager, normalDatabaseData); + int purgeCount = flatFileDatabaseManager.purgePowerlessUsers(); assertEquals(purgeCount, 1); //1 User should have been purged } @Test void testCheckFileHealthAndStructure() { - replaceDataInFile(db, badDatabaseData); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + replaceDataInFile(flatFileDatabaseManager, badDatabaseData); - List dataFlags = db.checkFileHealthAndStructure(); + List dataFlags = flatFileDatabaseManager.checkFileHealthAndStructure(); assertNotNull(dataFlags); assertNotEquals(dataFlags.size(), 0); } @Test void testFindFixableDuplicateNames() { - overwriteDataAndCheckForFlag(db, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateNameDatabaseData, FlatFileDataFlag.DUPLICATE_NAME); } @Test void testFindDuplicateUUIDs() { - overwriteDataAndCheckForFlag(db, duplicateUUIDDatabaseData, FlatFileDataFlag.DUPLICATE_UUID); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, duplicateUUIDDatabaseData, FlatFileDataFlag.DUPLICATE_UUID); } @Test() void findBadUUIDData() { - overwriteDataAndCheckForFlag(db, badUUIDDatabaseData, FlatFileDataFlag.BAD_UUID_DATA); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, badUUIDDatabaseData, FlatFileDataFlag.BAD_UUID_DATA); } @Test void testFindCorruptData() { - overwriteDataAndCheckForFlag(db, corruptDatabaseData, FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, corruptDatabaseData, FlatFileDataFlag.CORRUPTED_OR_UNRECOGNIZABLE); } @Test void testFindEmptyNames() { - overwriteDataAndCheckForFlag(db, emptyNameDatabaseData, FlatFileDataFlag.MISSING_NAME); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, emptyNameDatabaseData, FlatFileDataFlag.MISSING_NAME); } @Test void testFindBadValues() { - overwriteDataAndCheckForFlag(db, badDatabaseData, FlatFileDataFlag.BAD_VALUES); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, badDatabaseData, FlatFileDataFlag.BAD_VALUES); } @Test void testFindOutdatedData() { - overwriteDataAndCheckForFlag(db, outdatedDatabaseData, FlatFileDataFlag.INCOMPLETE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + overwriteDataAndCheckForFlag(flatFileDatabaseManager, outdatedDatabaseData, FlatFileDataFlag.INCOMPLETE); } @Test void testGetDatabaseType() { - assertNotNull(db); - assertEquals(db.getDatabaseType(), DatabaseType.FLATFILE); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + assertNotNull(flatFileDatabaseManager); + assertEquals(flatFileDatabaseManager.getDatabaseType(), DatabaseType.FLATFILE); } @Test void testReadRank() { //This is an empty DB - assertNotNull(db); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); String rankBoyName = "rankBoy"; UUID rankBoyUUID = new UUID(1337, 1337); String rankGirlName = "rankGirl"; @@ -658,12 +589,12 @@ class FlatFileDatabaseManagerTest { PlayerProfile rankGirlProfile = addPlayerProfileWithLevelsAndSave(rankGirlName, rankGirlUUID, 100); //Rank 1 PlayerProfile rankBoyProfile = addPlayerProfileWithLevelsAndSave(rankBoyName, rankBoyUUID, 10); //Rank 2 - assertEquals(LeaderboardStatus.UPDATED, db.updateLeaderboards()); - Map rankGirlPositions = db.readRank(rankGirlName); - Map rankBoyPositions = db.readRank(rankBoyName); + assertEquals(LeaderboardStatus.UPDATED, flatFileDatabaseManager.updateLeaderboards()); + Map rankGirlPositions = flatFileDatabaseManager.readRank(rankGirlName); + Map rankBoyPositions = flatFileDatabaseManager.readRank(rankBoyName); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(primarySkillType.isChildSkill()) { + if (primarySkillType.isChildSkill()) { assertNull(rankBoyPositions.get(primarySkillType)); assertNull(rankGirlPositions.get(primarySkillType)); } else { @@ -672,8 +603,8 @@ class FlatFileDatabaseManagerTest { } } - assertEquals(1, db.readRank(rankGirlName).get(null)); //Girl should be position 1 - assertEquals(2, db.readRank(rankBoyName).get(null)); //Boy should be position 2 + assertEquals(1, flatFileDatabaseManager.readRank(rankGirlName).get(null)); //Girl should be position 1 + assertEquals(2, flatFileDatabaseManager.readRank(rankBoyName).get(null)); //Boy should be position 2 } @Test @@ -692,7 +623,7 @@ class FlatFileDatabaseManagerTest { assertNotNull(resourceFileURI); File copyOfFile = new File(tempDir.getPath() + File.separator + DB_BADDATA); - if(copyOfFile.exists()) { + if (copyOfFile.exists()) { copyOfFile.delete(); } @@ -741,28 +672,28 @@ class FlatFileDatabaseManagerTest { } private @NotNull PlayerProfile addPlayerProfileWithLevelsAndSave(String playerName, UUID uuid, int levels) { - assertNotNull(db); - assertFalse(db.loadPlayerProfile(uuid).isLoaded()); + FlatFileDatabaseManager flatFileDatabaseManager = new FlatFileDatabaseManager(new File(getTemporaryUserFilePath()), logger, PURGE_TIME, 0, true); + assertFalse(flatFileDatabaseManager.loadPlayerProfile(uuid).isLoaded()); - db.newUser(playerName, uuid); - PlayerProfile leveledProfile = db.loadPlayerProfile(uuid); + flatFileDatabaseManager.newUser(playerName, uuid); + PlayerProfile leveledProfile = flatFileDatabaseManager.loadPlayerProfile(uuid); assertTrue(leveledProfile.isLoaded()); assertEquals(playerName, leveledProfile.getPlayerName()); assertEquals(uuid, leveledProfile.getUniqueId()); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) + if (SkillTools.isChildSkill(primarySkillType)) continue; leveledProfile.modifySkill(primarySkillType, levels); //TODO: This method also resets XP, not cool } - db.saveUser(leveledProfile); - leveledProfile = db.loadPlayerProfile(uuid); + flatFileDatabaseManager.saveUser(leveledProfile); + leveledProfile = flatFileDatabaseManager.loadPlayerProfile(uuid); for(PrimarySkillType primarySkillType : PrimarySkillType.values()) { - if(SkillTools.isChildSkill(primarySkillType)) { + if (SkillTools.isChildSkill(primarySkillType)) { continue; } diff --git a/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java new file mode 100644 index 000000000..c8125b763 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/PotionEffectUtilTest.java @@ -0,0 +1,57 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.compat.CompatibilityManager; +import com.gmail.nossr50.util.platform.MinecraftGameVersion; +import org.bukkit.potion.PotionEffectType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static com.gmail.nossr50.util.PotionEffectUtil.getNauseaPotionEffectType; +import static java.util.logging.Logger.getLogger; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.*; + +class PotionEffectUtilTest { + private MockedStatic mockedStaticMcMMO; + private static final java.util.logging.Logger logger = getLogger(PotionEffectUtilTest.class.getName()); + + @BeforeEach + void setUp() { + mockedStaticMcMMO = mockStatic(mcMMO.class); + mcMMO.p = mock(mcMMO.class); + when(mcMMO.p.getLogger()).thenReturn(logger); + CompatibilityManager compatibilityManager = mock(CompatibilityManager.class); + MinecraftGameVersion minecraftGameVersion = mock(MinecraftGameVersion.class); + when(compatibilityManager.getMinecraftGameVersion()).thenReturn(minecraftGameVersion); + when(minecraftGameVersion.isAtLeast(1, 20, 5)).thenReturn(false); + when(mcMMO.getCompatibilityManager()).thenReturn(compatibilityManager); + } + + @AfterEach + void tearDown() { + mockedStaticMcMMO.close(); + } + + @Test + @Tag("skip") + void testGetNauseaPotionEffectType() { + // TODO: Test only works on older versions since we aren't properly mocking the spigot registry + final PotionEffectType nausea = getNauseaPotionEffectType(); + assertNotNull(nausea); + assertThat(nausea).isEqualTo(PotionEffectType.NAUSEA); + } + + @Test + @Tag("skip") + void testGetHastePotionEffectType() { + // TODO: Test only works on older versions since we aren't properly mocking the spigot registry + final PotionEffectType haste = PotionEffectUtil.getHastePotionEffectType(); + assertNotNull(haste); + assertThat(haste).isEqualTo(PotionEffectType.HASTE); + } +} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java new file mode 100644 index 000000000..299496320 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/PotionUtilTest.java @@ -0,0 +1,70 @@ +package com.gmail.nossr50.util; + +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.compat.CompatibilityManager; +import com.gmail.nossr50.util.platform.MinecraftGameVersion; +import org.bukkit.potion.PotionType; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static com.gmail.nossr50.util.PotionUtil.convertLegacyNames; +import static com.gmail.nossr50.util.PotionUtil.matchPotionType; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.*; + +class PotionUtilTest { + + MockedStatic mockedStaticMcMMO; + + @BeforeEach + void setUp() { + mockedStaticMcMMO = mockStatic(mcMMO.class); + CompatibilityManager compatibilityManager = mock(CompatibilityManager.class); + MinecraftGameVersion minecraftGameVersion = mock(MinecraftGameVersion.class); + when(compatibilityManager.getMinecraftGameVersion()).thenReturn(minecraftGameVersion); + when(minecraftGameVersion.isAtLeast(1, 20, 5)).thenReturn(true); + when(mcMMO.getCompatibilityManager()).thenReturn(compatibilityManager); + } + + @AfterEach + void tearDown() { + mockedStaticMcMMO.close(); + } + + @Test + void testMatchPotionTypeStrengthII() { + final String potionTypeStr = "STRENGTH"; + final PotionType potionType = matchPotionType(potionTypeStr, true, false); + assertEquals(PotionType.STRONG_STRENGTH, potionType); + } + + @Test + void testMatchPotionTypeRegen() { + final String potionTypeStr = "REGEN"; + final PotionType potionType = matchPotionType(potionTypeStr, false, false); + assertEquals(PotionType.REGENERATION, potionType); + } + + @Test + void testMatchPotionTypeUncraftable() { + final String potionTypeStr = "UNCRAFTABLE"; + final PotionType potionType = matchPotionType(potionTypeStr, false, false); + assertEquals(PotionType.MUNDANE, potionType); + } + + @Test + void testConvertLegacyNamesUncraftable() { + final String potionTypeStr = "UNCRAFTABLE"; + final String converted = convertLegacyNames(potionTypeStr); + assertEquals("MUNDANE", converted); + } + + @Test + void testConvertLegacyNamesRegen() { + final String potionTypeStr = "REGEN"; + final String converted = convertLegacyNames(potionTypeStr); + assertEquals("REGENERATION", converted); + } +} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java new file mode 100644 index 000000000..9e266d8d6 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/BitSetChunkStoreTest.java @@ -0,0 +1,121 @@ +package com.gmail.nossr50.util.blockmeta; + +import com.gmail.nossr50.mcMMO; +import com.google.common.io.Files; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.junit.jupiter.api.*; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.*; +import static com.gmail.nossr50.util.blockmeta.UserBlockTrackerTest.recursiveDelete; +import static org.bukkit.Bukkit.getWorld; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +class BitSetChunkStoreTest { + private static File tempDir; + + @BeforeAll + public static void setUpClass() { + tempDir = Files.createTempDir(); + } + + @AfterAll + public static void tearDownClass() { + recursiveDelete(tempDir); + } + + private World mockWorld; + + private MockedStatic bukkitMock; + private MockedStatic mcMMOMock; + + @BeforeEach + void setUpMock() { + UUID worldUUID = UUID.randomUUID(); + mockWorld = Mockito.mock(World.class); + when(mockWorld.getUID()).thenReturn(worldUUID); + when(mockWorld.getMaxHeight()).thenReturn(256); + when(mockWorld.getWorldFolder()).thenReturn(tempDir); + + bukkitMock = mockStatic(Bukkit.class); + bukkitMock.when(() -> getWorld(worldUUID)).thenReturn(mockWorld); + + mcMMOMock = mockStatic(mcMMO.class); + + when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); + when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); + } + + @AfterEach + void teardownMock() { + bukkitMock.close(); + mcMMOMock.close(); + } + + @Test + void testSetValue() { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); + original.setTrue(0, 0, 0); + assertTrue(original.isTrue(0, 0, 0)); + original.setFalse(0, 0, 0); + assertFalse(original.isTrue(0, 0, 0)); + } + + @Test + void testIsEmpty() { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); + assertTrue(original.isEmpty()); + original.setTrue(0, 0, 0); + original.setFalse(0, 0, 0); + assertTrue(original.isEmpty()); + } + + @Test + void testRoundTrip() throws IOException { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); + original.setTrue(14, 89, 12); + original.setTrue(14, 90, 12); + original.setTrue(13, 89, 12); + byte[] serializedBytes = serializeChunkStore(original); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + assertChunkStoreEquals(original, deserialized); + } + + @Test + void testNegativeWorldMin() throws IOException { + when(mockWorld.getMinHeight()).thenReturn(-64); + + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); + original.setTrue(14, -32, 12); + original.setTrue(14, -64, 12); + original.setTrue(13, -63, 12); + byte[] serializedBytes = serializeChunkStore(original); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + assertChunkStoreEquals(original, deserialized); + } + + @Test + void testNegativeWorldMinUpgrade() throws IOException { + final BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); + original.setTrue(14, 1, 12); + original.setTrue(14, 2, 12); + original.setTrue(13, 3, 12); + byte[] serializedBytes = serializeChunkStore(original); + + when(mockWorld.getMinHeight()).thenReturn(-64); + final ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); + assert deserialized != null; + assertEqualIgnoreMinMax(original, deserialized); + } +} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java b/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java new file mode 100644 index 000000000..709a7b57f --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/BlockStoreTestUtils.java @@ -0,0 +1,49 @@ +package com.gmail.nossr50.util.blockmeta; + +import org.jetbrains.annotations.NotNull; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BlockStoreTestUtils { + public static final int LEGACY_WORLD_HEIGHT_MAX = 256; + public static final int LEGACY_WORLD_HEIGHT_MIN = 0; + + /** + * Asserts that the two ChunkStores are equal. + * @param expected The expected ChunkStore + * @param actual The actual ChunkStore + */ + static void assertChunkStoreEquals(ChunkStore expected, ChunkStore actual) { + assertEquals(expected.getChunkMin(), actual.getChunkMin()); + assertEquals(expected.getChunkMax(), actual.getChunkMax()); + assertEqualIgnoreMinMax(expected, actual); + } + + static byte[] serializeChunkStore(@NotNull ChunkStore chunkStore) throws IOException { + final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + if (chunkStore instanceof BitSetChunkStore) + BitSetChunkStore.Serialization.writeChunkStore(new DataOutputStream(byteArrayOutputStream), chunkStore); + else + new UnitTestObjectOutputStream(byteArrayOutputStream).writeObject(chunkStore); // Serializes the class as if + // it were the old + // PrimitiveChunkStore + return byteArrayOutputStream.toByteArray(); + } + + static void assertEqualIgnoreMinMax(ChunkStore expected, ChunkStore actual) { + assertEquals(expected.getChunkX(), actual.getChunkX()); + assertEquals(expected.getChunkZ(), actual.getChunkZ()); + assertEquals(expected.getWorldId(), actual.getWorldId()); + for (int y = Math.min(actual.getChunkMin(), expected.getChunkMin()); y < Math.max(actual.getChunkMax(), expected.getChunkMax()); y++) { + if (expected.getChunkMin() > y || actual.getChunkMin() > y || expected.getChunkMax() <= y || actual.getChunkMax() <= y) + continue; // Ignore + for (int x = 0; x < 16; x++) + for (int z = 0; z < 16; z++) + assertEquals(expected.isTrue(x, y, z), actual.isTrue(x, y, z)); + } + } +} diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java index 969de6ec4..f7f369076 100644 --- a/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/ChunkStoreTest.java @@ -1,13 +1,9 @@ package com.gmail.nossr50.util.blockmeta; - import com.gmail.nossr50.mcMMO; -import com.gmail.nossr50.util.BlockUtils; import com.google.common.io.Files; import org.bukkit.Bukkit; import org.bukkit.World; -import org.bukkit.block.Block; -import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.*; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -15,14 +11,13 @@ import org.mockito.Mockito; import java.io.*; import java.util.UUID; -/** - * Could be a lot better. But some tests are better than none! Tests the major things, still kinda unit-testy. Verifies - * that the serialization isn't completely broken. - */ -class ChunkStoreTest { +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.*; +import static com.gmail.nossr50.util.blockmeta.UserBlockTrackerTest.recursiveDelete; +import static org.bukkit.Bukkit.getWorld; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; - public static final int LEGACY_WORLD_HEIGHT_MAX = 256; - public static final int LEGACY_WORLD_HEIGHT_MIN = 0; +class ChunkStoreTest { private static File tempDir; @BeforeAll @@ -44,151 +39,39 @@ class ChunkStoreTest { void setUpMock() { UUID worldUUID = UUID.randomUUID(); mockWorld = Mockito.mock(World.class); - Mockito.when(mockWorld.getUID()).thenReturn(worldUUID); - Mockito.when(mockWorld.getMaxHeight()).thenReturn(256); - Mockito.when(mockWorld.getWorldFolder()).thenReturn(tempDir); + when(mockWorld.getUID()).thenReturn(worldUUID); + when(mockWorld.getMaxHeight()).thenReturn(256); + when(mockWorld.getWorldFolder()).thenReturn(tempDir); - bukkitMock = Mockito.mockStatic(Bukkit.class); - bukkitMock.when(() -> Bukkit.getWorld(worldUUID)).thenReturn(mockWorld); + bukkitMock = mockStatic(Bukkit.class); + bukkitMock.when(() -> getWorld(worldUUID)).thenReturn(mockWorld); - mcMMOMock = Mockito.mockStatic(mcMMO.class); + mcMMOMock = mockStatic(mcMMO.class); - Mockito.when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); - Mockito.when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); + when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); + when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); } - + @AfterEach void teardownMock() { bukkitMock.close(); mcMMOMock.close(); } - @Test - void testIndexOutOfBounds() { - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - HashChunkManager hashChunkManager = new HashChunkManager(); - - // Top Block - Block illegalHeightBlock = initMockBlock(1337, 256, -1337); - Assertions.assertFalse(hashChunkManager.isTrue(illegalHeightBlock)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> hashChunkManager.setTrue(illegalHeightBlock)); - } - - @Test - void testSetTrue() { - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - HashChunkManager hashChunkManager = new HashChunkManager(); - int radius = 2; // Could be anything but drastically changes test time - - for (int x = -radius; x <= radius; x++) { - for (int y = mockWorld.getMinHeight(); y < mockWorld.getMaxHeight(); y++) { - for (int z = -radius; z <= radius; z++) { - Block testBlock = initMockBlock(x, y, z); - - hashChunkManager.setTrue(testBlock); - Assertions.assertTrue(hashChunkManager.isTrue(testBlock)); - hashChunkManager.setFalse(testBlock); - Assertions.assertFalse(hashChunkManager.isTrue(testBlock)); - } - } - } - - // Bot Block - Block bottomBlock = initMockBlock(1337, 0, -1337); - Assertions.assertFalse(hashChunkManager.isTrue(bottomBlock)); - - Assertions.assertTrue(BlockUtils.isWithinWorldBounds(bottomBlock)); - hashChunkManager.setTrue(bottomBlock); - Assertions.assertTrue(hashChunkManager.isTrue(bottomBlock)); - - // Top Block - Block topBlock = initMockBlock(1337, 255, -1337); - Assertions.assertFalse(hashChunkManager.isTrue(topBlock)); - - Assertions.assertTrue(BlockUtils.isWithinWorldBounds(topBlock)); - hashChunkManager.setTrue(topBlock); - Assertions.assertTrue(hashChunkManager.isTrue(topBlock)); - } - - @Test - void testSetValue() { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); - original.setTrue(0, 0, 0); - Assertions.assertTrue(original.isTrue(0, 0, 0)); - original.setFalse(0, 0, 0); - Assertions.assertFalse(original.isTrue(0, 0, 0)); - } - - @Test - void testIsEmpty() { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 0, 0); - Assertions.assertTrue(original.isEmpty()); - original.setTrue(0, 0, 0); - original.setFalse(0, 0, 0); - Assertions.assertTrue(original.isEmpty()); - } - - @Test - void testRoundTrip() throws IOException { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); - original.setTrue(14, 89, 12); - original.setTrue(14, 90, 12); - original.setTrue(13, 89, 12); - byte[] serializedBytes = serializeChunkstore(original); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); - assertEqual(original, deserialized); - } - - @Test - void testNegativeWorldMin() throws IOException { - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); - original.setTrue(14, -32, 12); - original.setTrue(14, -64, 12); - original.setTrue(13, -63, 12); - byte[] serializedBytes = serializeChunkstore(original); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); - assertEqual(original, deserialized); - } - - @Test - void testNegativeWorldMinUpgrade() throws IOException { - BitSetChunkStore original = new BitSetChunkStore(mockWorld, 1, 2); - original.setTrue(14, 1, 12); - original.setTrue(14, 2, 12); - original.setTrue(13, 3, 12); - byte[] serializedBytes = serializeChunkstore(original); - - Mockito.when(mockWorld.getMinHeight()).thenReturn(-64); - ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); - assert deserialized != null; - assertEqualIgnoreMinMax(original, deserialized); - } - - @Test - void testChunkCoords() throws IOException { - for (int x = -96; x < 0; x++) { - int cx = x >> 4; - int ix = Math.abs(x) % 16; - //System.out.print(cx + ":" + ix + " "); - } - } - @Test void testUpgrade() throws IOException { LegacyChunkStore original = new LegacyChunkStore(mockWorld, 12, 32); original.setTrue(14, 89, 12); original.setTrue(14, 90, 12); original.setTrue(13, 89, 12); - byte[] serializedBytes = serializeChunkstore(original); + byte[] serializedBytes = serializeChunkStore(original); ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(new DataInputStream(new ByteArrayInputStream(serializedBytes))); assert deserialized != null; - assertEqual(original, deserialized); + assertChunkStoreEquals(original, deserialized); } @Test - void testSimpleRegionRoundtrip() throws IOException { + void testSimpleRegionRoundTrip() throws IOException { LegacyChunkStore original = new LegacyChunkStore(mockWorld, 12, 12); original.setTrue(14, 89, 12); original.setTrue(14, 90, 12); @@ -196,7 +79,7 @@ class ChunkStoreTest { File file = new File(tempDir, "SimpleRegionRoundTrip.region"); McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); try (DataOutputStream outputStream = region.getOutputStream(12, 12)) { - outputStream.write(serializeChunkstore(original)); + outputStream.write(serializeChunkStore(original)); } region.close(); region = new McMMOSimpleRegionFile(file, 0, 0); @@ -204,229 +87,10 @@ class ChunkStoreTest { Assertions.assertNotNull(is); ChunkStore deserialized = BitSetChunkStore.Serialization.readChunkStore(is); assert deserialized != null; - assertEqual(original, deserialized); + assertChunkStoreEquals(original, deserialized); } region.close(); file.delete(); } - @Test - void testSimpleRegionRejectsOutOfBounds() { - File file = new File(tempDir, "SimpleRegionRoundTrip.region"); - McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(-1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, -1)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(32, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, 32)); - region.close(); - } - - @Test - void testChunkStoreRejectsOutOfBounds() { - ChunkStore chunkStore = new BitSetChunkStore(mockWorld, 0, 0); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(-1, 0, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, -1, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, -1)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(16, 0, 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, mockWorld.getMaxHeight(), 0)); - Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, 16)); - } - - @Test - void testRegressionChunkMirrorBug() { - ChunkManager chunkManager = new HashChunkManager(); - Block mockBlockA = Mockito.mock(Block.class); - Mockito.when(mockBlockA.getX()).thenReturn(15); - Mockito.when(mockBlockA.getZ()).thenReturn(15); - Mockito.when(mockBlockA.getY()).thenReturn(0); - Mockito.when(mockBlockA.getWorld()).thenReturn(mockWorld); - Block mockBlockB = Mockito.mock(Block.class); - Mockito.when(mockBlockB.getX()).thenReturn(-15); - Mockito.when(mockBlockB.getZ()).thenReturn(-15); - Mockito.when(mockBlockB.getY()).thenReturn(0); - Mockito.when(mockBlockB.getWorld()).thenReturn(mockWorld); - - chunkManager.setTrue(mockBlockA); - chunkManager.setFalse(mockBlockB); - Assertions.assertTrue(chunkManager.isTrue(mockBlockA)); - } - - private void assertEqual(ChunkStore expected, ChunkStore actual) { - Assertions.assertEquals(expected.getChunkMin(), actual.getChunkMin()); - Assertions.assertEquals(expected.getChunkMax(), actual.getChunkMax()); - assertEqualIgnoreMinMax(expected, actual); - } - - private void assertEqualIgnoreMinMax(ChunkStore expected, ChunkStore actual) { - Assertions.assertEquals(expected.getChunkX(), actual.getChunkX()); - Assertions.assertEquals(expected.getChunkZ(), actual.getChunkZ()); - Assertions.assertEquals(expected.getWorldId(), actual.getWorldId()); - for (int y = Math.min(actual.getChunkMin(), expected.getChunkMin()); y < Math.max(actual.getChunkMax(), expected.getChunkMax()); y++) { - if (expected.getChunkMin() > y || actual.getChunkMin() > y || expected.getChunkMax() <= y || actual.getChunkMax() <= y) - continue; // Ignore - for (int x = 0; x < 16; x++) - for (int z = 0; z < 16; z++) - Assertions.assertEquals(expected.isTrue(x, y, z), actual.isTrue(x, y, z)); - } - } - - private static byte[] serializeChunkstore(@NotNull ChunkStore chunkStore) throws IOException { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - if (chunkStore instanceof BitSetChunkStore) - BitSetChunkStore.Serialization.writeChunkStore(new DataOutputStream(byteArrayOutputStream), chunkStore); - else - new UnitTestObjectOutputStream(byteArrayOutputStream).writeObject(chunkStore); // Serializes the class as if - // it were the old - // PrimitiveChunkStore - return byteArrayOutputStream.toByteArray(); - } - - public static class LegacyChunkStore implements ChunkStore, Serializable { - private static final long serialVersionUID = -1L; - transient private boolean dirty = false; - public boolean[][][] store; - private static final int CURRENT_VERSION = 7; - private static final int MAGIC_NUMBER = 0xEA5EDEBB; - private final int cx; - private final int cz; - private final @NotNull UUID worldUid; - - public LegacyChunkStore(@NotNull World world, int cx, int cz) { - this.cx = cx; - this.cz = cz; - this.worldUid = world.getUID(); - this.store = new boolean[16][16][world.getMaxHeight()]; - } - - @Override - public boolean isDirty() { - return dirty; - } - - @Override - public void setDirty(boolean dirty) { - this.dirty = dirty; - } - - @Override - public int getChunkX() { - return cx; - } - - @Override - public int getChunkZ() { - return cz; - } - - @Override - public int getChunkMin() { - return 0; - } - - @Override - public int getChunkMax() { - return store[0][0].length; - } - - @Override - public @NotNull UUID getWorldId() { - return worldUid; - } - - @Override - public boolean isTrue(int x, int y, int z) { - return store[x][z][y]; - } - - @Override - public void setTrue(int x, int y, int z) { - if (y >= store[0][0].length || y < 0) - return; - store[x][z][y] = true; - dirty = true; - } - - @Override - public void setFalse(int x, int y, int z) { - if (y >= store[0][0].length || y < 0) - return; - store[x][z][y] = false; - dirty = true; - } - - @Override - public void set(int x, int y, int z, boolean value) { - if (y >= store[0][0].length || y < 0) - return; - store[x][z][y] = value; - dirty = true; - } - - @Override - public boolean isEmpty() { - for (int x = 0; x < 16; x++) { - for (int z = 0; z < 16; z++) { - for (int y = 0; y < store[0][0].length; y++) { - if (store[x][z][y]) { - return false; - } - } - } - } - return true; - } - - private void writeObject(@NotNull ObjectOutputStream out) throws IOException { - out.writeInt(MAGIC_NUMBER); - out.writeInt(CURRENT_VERSION); - - out.writeLong(worldUid.getLeastSignificantBits()); - out.writeLong(worldUid.getMostSignificantBits()); - out.writeInt(cx); - out.writeInt(cz); - out.writeObject(store); - - dirty = false; - } - - private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException { - throw new UnsupportedOperationException(); - } - - } - - private static class UnitTestObjectOutputStream extends ObjectOutputStream { - - public UnitTestObjectOutputStream(@NotNull OutputStream outputStream) throws IOException { - super(outputStream); - } - - @Override - public void writeUTF(@NotNull String str) throws IOException { - // Pretend to be the old class - if (str.equals(LegacyChunkStore.class.getName())) - str = "com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore"; - super.writeUTF(str); - } - - } - - @NotNull - private Block initMockBlock(int x, int y, int z) { - Block mockBlock = Mockito.mock(Block.class); - Mockito.when(mockBlock.getX()).thenReturn(x); - Mockito.when(mockBlock.getY()).thenReturn(y); - Mockito.when(mockBlock.getZ()).thenReturn(z); - Mockito.when(mockBlock.getWorld()).thenReturn(mockWorld); - return mockBlock; - } - - public static void recursiveDelete(@NotNull File directoryToBeDeleted) { - if (directoryToBeDeleted.isDirectory()) { - for (File file : directoryToBeDeleted.listFiles()) { - recursiveDelete(file); - } - } - directoryToBeDeleted.delete(); - } -} +} \ No newline at end of file diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java b/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java new file mode 100644 index 000000000..b21cf2594 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/LegacyChunkStore.java @@ -0,0 +1,127 @@ +package com.gmail.nossr50.util.blockmeta; + +import org.bukkit.World; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.UUID; + +/** + * Used for unit testing upgrades from the old ChunkStore class. + */ +class LegacyChunkStore implements ChunkStore, Serializable { + private static final long serialVersionUID = -1L; + transient private boolean dirty = false; + public boolean[][][] store; + private static final int CURRENT_VERSION = 7; + private static final int MAGIC_NUMBER = 0xEA5EDEBB; + private final int cx; + private final int cz; + private final @NotNull UUID worldUid; + + public LegacyChunkStore(@NotNull World world, int cx, int cz) { + this.cx = cx; + this.cz = cz; + this.worldUid = world.getUID(); + this.store = new boolean[16][16][world.getMaxHeight()]; + } + + @Override + public boolean isDirty() { + return dirty; + } + + @Override + public void setDirty(boolean dirty) { + this.dirty = dirty; + } + + @Override + public int getChunkX() { + return cx; + } + + @Override + public int getChunkZ() { + return cz; + } + + @Override + public int getChunkMin() { + return 0; + } + + @Override + public int getChunkMax() { + return store[0][0].length; + } + + @Override + public @NotNull UUID getWorldId() { + return worldUid; + } + + @Override + public boolean isTrue(int x, int y, int z) { + return store[x][z][y]; + } + + @Override + public void setTrue(int x, int y, int z) { + if (y >= store[0][0].length || y < 0) + return; + store[x][z][y] = true; + dirty = true; + } + + @Override + public void setFalse(int x, int y, int z) { + if (y >= store[0][0].length || y < 0) + return; + store[x][z][y] = false; + dirty = true; + } + + @Override + public void set(int x, int y, int z, boolean value) { + if (y >= store[0][0].length || y < 0) + return; + store[x][z][y] = value; + dirty = true; + } + + @Override + public boolean isEmpty() { + for (int x = 0; x < 16; x++) { + for (int z = 0; z < 16; z++) { + for (int y = 0; y < store[0][0].length; y++) { + if (store[x][z][y]) { + return false; + } + } + } + } + return true; + } + + private void writeObject(@NotNull ObjectOutputStream out) throws IOException { + out.writeInt(MAGIC_NUMBER); + out.writeInt(CURRENT_VERSION); + + out.writeLong(worldUid.getLeastSignificantBits()); + out.writeLong(worldUid.getMostSignificantBits()); + out.writeInt(cx); + out.writeInt(cz); + out.writeObject(store); + + dirty = false; + } + + private void readObject(@NotNull ObjectInputStream in) throws IOException, ClassNotFoundException { + throw new UnsupportedOperationException(); + } + +} diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java b/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java new file mode 100644 index 000000000..d7eb1c140 --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/UnitTestObjectOutputStream.java @@ -0,0 +1,23 @@ +package com.gmail.nossr50.util.blockmeta; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.OutputStream; + +class UnitTestObjectOutputStream extends ObjectOutputStream { + + public UnitTestObjectOutputStream(@NotNull OutputStream outputStream) throws IOException { + super(outputStream); + } + + @Override + public void writeUTF(@NotNull String str) throws IOException { + // Pretend to be the old class + if (str.equals(LegacyChunkStore.class.getName())) + str = "com.gmail.nossr50.util.blockmeta.chunkmeta.PrimitiveChunkStore"; + super.writeUTF(str); + } + +} diff --git a/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java b/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java new file mode 100644 index 000000000..89a2f63ff --- /dev/null +++ b/src/test/java/com/gmail/nossr50/util/blockmeta/UserBlockTrackerTest.java @@ -0,0 +1,192 @@ +package com.gmail.nossr50.util.blockmeta; + +import com.gmail.nossr50.mcMMO; +import com.gmail.nossr50.util.BlockUtils; +import com.google.common.io.Files; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.jetbrains.annotations.NotNull; +import org.junit.jupiter.api.*; +import org.mockito.MockedStatic; +import org.mockito.Mockito; + +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MAX; +import static com.gmail.nossr50.util.blockmeta.BlockStoreTestUtils.LEGACY_WORLD_HEIGHT_MIN; +import static org.bukkit.Bukkit.getWorld; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Could be a lot better. But some tests are better than none! Tests the major things, still kinda unit-testy. Verifies + * that the serialization isn't completely broken. + */ +class UserBlockTrackerTest { + private static File tempDir; + + @BeforeAll + public static void setUpClass() { + tempDir = Files.createTempDir(); + } + + @AfterAll + public static void tearDownClass() { + recursiveDelete(tempDir); + } + + private World mockWorld; + + private MockedStatic bukkitMock; + private MockedStatic mcMMOMock; + + @BeforeEach + void setUpMock() { + UUID worldUUID = UUID.randomUUID(); + mockWorld = Mockito.mock(World.class); + when(mockWorld.getUID()).thenReturn(worldUUID); + when(mockWorld.getMaxHeight()).thenReturn(256); + when(mockWorld.getWorldFolder()).thenReturn(tempDir); + + bukkitMock = mockStatic(Bukkit.class); + bukkitMock.when(() -> getWorld(worldUUID)).thenReturn(mockWorld); + + mcMMOMock = mockStatic(mcMMO.class); + + when(mockWorld.getMinHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MIN); + when(mockWorld.getMaxHeight()).thenReturn(LEGACY_WORLD_HEIGHT_MAX); + } + + @AfterEach + void teardownMock() { + bukkitMock.close(); + mcMMOMock.close(); + } + + @Test + void setIneligibleShouldThrowIndexOutOfBoundsException() { + when(mockWorld.getMinHeight()).thenReturn(-64); + final HashChunkManager hashChunkManager = new HashChunkManager(); + + // Top Block + final Block illegalHeightBlock = initMockBlock(1337, 256, -1337); + assertFalse(hashChunkManager.isIneligible(illegalHeightBlock)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> hashChunkManager.setIneligible(illegalHeightBlock)); + } + + @Test + void testSetEligibility() { + when(mockWorld.getMinHeight()).thenReturn(-64); + final HashChunkManager hashChunkManager = new HashChunkManager(); + int radius = 2; // Could be anything but drastically changes test time + + for (int x = -radius; x <= radius; x++) { + for (int y = mockWorld.getMinHeight(); y < mockWorld.getMaxHeight(); y++) { + for (int z = -radius; z <= radius; z++) { + final Block testBlock = initMockBlock(x, y, z); + // mark ineligible + hashChunkManager.setIneligible(testBlock); + assertTrue(hashChunkManager.isIneligible(testBlock)); + + // mark eligible + hashChunkManager.setEligible(testBlock); + // Might as well test both isIneligible and isEligible while we are here + assertFalse(hashChunkManager.isIneligible(testBlock)); + assertTrue(hashChunkManager.isEligible(testBlock)); + } + } + } + + // TODO: Whatever is going on down here should be in its own test + // Bot Block + final Block bottomBlock = initMockBlock(1337, 0, -1337); + assertFalse(hashChunkManager.isIneligible(bottomBlock)); + + assertTrue(BlockUtils.isWithinWorldBounds(bottomBlock)); + hashChunkManager.setIneligible(bottomBlock); + assertTrue(hashChunkManager.isIneligible(bottomBlock)); + + // Top Block + final Block topBlock = initMockBlock(1337, 255, -1337); + assertFalse(hashChunkManager.isIneligible(topBlock)); + + assertTrue(BlockUtils.isWithinWorldBounds(topBlock)); + hashChunkManager.setIneligible(topBlock); + assertTrue(hashChunkManager.isIneligible(topBlock)); + } + + @Test + void testChunkCoords() throws IOException { + // TODO: Unfinished test? + for (int x = -96; x < 0; x++) { + int cx = x >> 4; + int ix = Math.abs(x) % 16; + //System.out.print(cx + ":" + ix + " "); + } + } + + @Test + void testSimpleRegionRejectsOutOfBounds() { + File file = new File(tempDir, "SimpleRegionRoundTrip.region"); + McMMOSimpleRegionFile region = new McMMOSimpleRegionFile(file, 0, 0); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(-1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, -1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(32, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> region.getOutputStream(0, 32)); + region.close(); + } + + @Test + void testChunkStoreRejectsOutOfBounds() { + ChunkStore chunkStore = new BitSetChunkStore(mockWorld, 0, 0); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(-1, 0, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, -1, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, -1)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(16, 0, 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, mockWorld.getMaxHeight(), 0)); + Assertions.assertThrows(IndexOutOfBoundsException.class, () -> chunkStore.setTrue(0, 0, 16)); + } + + @Test + void testRegressionChunkMirrorBug() { + final UserBlockTracker chunkManager = new HashChunkManager(); + Block mockBlockA = Mockito.mock(Block.class); + when(mockBlockA.getX()).thenReturn(15); + when(mockBlockA.getZ()).thenReturn(15); + when(mockBlockA.getY()).thenReturn(0); + when(mockBlockA.getWorld()).thenReturn(mockWorld); + Block mockBlockB = Mockito.mock(Block.class); + when(mockBlockB.getX()).thenReturn(-15); + when(mockBlockB.getZ()).thenReturn(-15); + when(mockBlockB.getY()).thenReturn(0); + when(mockBlockB.getWorld()).thenReturn(mockWorld); + + chunkManager.setIneligible(mockBlockA); + chunkManager.setEligible(mockBlockB); + assertTrue(chunkManager.isIneligible(mockBlockA)); + } + + @NotNull + private Block initMockBlock(int x, int y, int z) { + final Block mockBlock = Mockito.mock(Block.class); + when(mockBlock.getX()).thenReturn(x); + when(mockBlock.getY()).thenReturn(y); + when(mockBlock.getZ()).thenReturn(z); + when(mockBlock.getWorld()).thenReturn(mockWorld); + return mockBlock; + } + + public static void recursiveDelete(@NotNull File directoryToBeDeleted) { + if (directoryToBeDeleted.isDirectory()) { + for (File file : directoryToBeDeleted.listFiles()) { + recursiveDelete(file); + } + } + directoryToBeDeleted.delete(); + } +} diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java index e114313ba..0a128cd52 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTest.java @@ -93,7 +93,7 @@ class ProbabilityTest { double winCount = 0; for (int i = 0; i < iterations; i++) { - if(probability.evaluate()) { + if (probability.evaluate()) { winCount++; } } diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java index e97119be6..32dadfbbd 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityTestUtils.java @@ -7,7 +7,7 @@ public class ProbabilityTestUtils { double iterations = 2.0e7; //20 million double winCount = 0; for (int i = 0; i < iterations; i++) { - if(probability.evaluate()) { + if (probability.evaluate()) { winCount++; } } @@ -16,7 +16,7 @@ public class ProbabilityTestUtils { System.out.println("Wins: " + winCount); System.out.println("Fails: " + (iterations - winCount)); System.out.println("Percentage succeeded: " + successPercent + ", Expected: " + expectedWinPercent); - assertEquals(expectedWinPercent, successPercent, 0.025D); + assertEquals(expectedWinPercent, successPercent, 0.035D); System.out.println("Variance is within tolerance levels!"); } } diff --git a/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java b/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java index 4994f8053..44420a093 100644 --- a/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java +++ b/src/test/java/com/gmail/nossr50/util/random/ProbabilityUtilTest.java @@ -62,7 +62,8 @@ class ProbabilityUtilTest extends MMOTestEnvironment { when(advancedConfig.getMaximumProbability(UNARMED_ARROW_DEFLECT)).thenReturn(20D); when(advancedConfig.getMaxBonusLevel(UNARMED_ARROW_DEFLECT)).thenReturn(0); - final Probability probability = ProbabilityUtil.getSkillProbability(UNARMED_ARROW_DEFLECT, player); + @SuppressWarnings("all") + final Probability probability = ProbabilityUtil.getSkillProbability(UNARMED_ARROW_DEFLECT, mmoPlayer); assertEquals(0.2D, probability.getValue()); assertProbabilityExpectations(20, probability); } diff --git a/src/test/resources/healthydb.users b/src/test/resources/healthydb.users index 79a2c7e70..c2561b38d 100644 --- a/src/test/resources/healthydb.users +++ b/src/test/resources/healthydb.users @@ -1,3 +1,3 @@ -nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:IGNORED:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:2020:140:14:150:15:1111:2222:3333: -mrfloris:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:631e3896-da2a-4077-974b-d047859d76bc:5:1600906906:3030:0:0:0:0:0:0:0: -powerless:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:1337:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:5:1600906906:4040:0:0:0:0:0:0:0: \ No newline at end of file +nossr50:1:IGNORED:IGNORED:10:2:20:3:4:5:6:7:8:9:10:30:40:50:60:70:80:90:100:IGNORED:11:110:111:222:333:444:555:666:777:IGNORED:12:120:888:IGNORED:HEARTS:13:130:588fe472-1c82-4c4e-9aa1-7eefccb277e3:1111:999:2020:140:14:150:15:1111:2222:3333:160:16:4444: +mrfloris:2420:::0:2452:0:1983:1937:1790:3042:1138:3102:2408:3411:0:0:0:0:0:0:0:0::642:0:1617583171:0:1617165043:0:1617583004:1617563189:1616785408::2184:0:0:1617852413:HEARTS:415:0:631e3896-da2a-4077-974b-d047859d76bc:5:1600906906:3030:0:0:0:0:0:0:0:0:0:0: +powerless:0:::0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0::0:0:0:0:0:0:0:0:0::0:0:0:1337:HEARTS:0:0:e0d07db8-f7e8-43c7-9ded-864dfc6f3b7c:5:1600906906:4040:0:0:0:0:0:0:0:0:0:0: \ No newline at end of file